import { View, Text, ScrollView, StyleSheet, ActivityIndicator, Pressable, Image } from 'react-native';

import { SafeAreaView } from 'react-native-safe-area-context';
import NormalButton from '../global/normal_button';
import { router, useFocusEffect } from 'expo-router';
import { useCallback, useEffect, useState } from 'react';
import { chargeStationService } from '../../service/chargeStationService';

// const RETRY_DELAY = 2000; // 2 seconds
// const MAX_RETRIES = 3; // Maximum number of retry attempts

const NoChargingOngoingPageComponent = () => {
    const [newAvailableConnectors, setNewAvailableConnectors] = useState([]);
    useFocusEffect(
        useCallback(() => {
            let isMounted = true; // Simple cleanup flag
            const fetchAllConnectors = async () => {
                try {
                    const newAvailableConnectors = await chargeStationService.NewfetchAvailableConnectors();

                    // Only update state if component is still mounted
                    if (isMounted) {
                        // Sort the connectors based on stationID
                        const sortedConnectors = [...newAvailableConnectors].sort((a, b) => {
                            // Custom sorting order
                            const order = {
                                '2405311022116801000': 1, // 觀塘偉業街
                                '2411291610329331000': 2, // 黃竹坑
                                '2501161430118231000': 3 // 沙頭角
                            };
                            return (order[a.stationID] || 999) - (order[b.stationID] || 999);
                        });

                        setNewAvailableConnectors(sortedConnectors);
                    }
                } catch (error) {
                    console.error('Fetch error:', error);
                }
            };

            fetchAllConnectors();

            // Simple cleanup - prevents state updates if component unmounts
            return () => {
                isMounted = false;
            };
        }, []) // Add any missing dependencies here if needed
    );

    const StationRow = ({ item, index }: { item: any, index: number }) => {
        // const imageSource = stationImages[stationID] || require('../../assets/dummyStationPicture.png');
        console.log('image', item.image, item.stationName);
        let imgObj = null
        if (item.image) {
            imgObj = {uri: item.image}
        } else {
            imgObj = require('../../assets/dummyStationPicture.png')
        }
        return (
            <Pressable
                onPress={() => {
                    router.push({
                        pathname: '/resultDetailPage',
                        params: {
                            chargeStationAddress: item.address,
                            chargeStationID: item.stationID,
                            chargeStationName: item.stationName,
                            availableConnectors: item.availableConnectors,
                            // imageSource: imageSource
                            imageSource: item.image,
                            stationLng: item.stationLng,
                            stationLat: item.stationLat
                        }
                    });
                }}
            >
                <View className="flex flex-1 flex-row w-full ">
                    <Image style={styles.image} source={imgObj} key={index} />
                    <View className="flex flex-col gap-2 mt-5 mr-2">
                        <Text
                            style={{
                                fontWeight: '700',
                                color: '#02677D',
                                fontSize: 20
                            }}
                        >
                            {item.stationName}
                        </Text>
                        <View className="flex flex-row justify-between space-x-2">
                            <Text
                                style={{
                                    fontWeight: '400',
                                    fontSize: 16,
                                    color: '#222222'
                                }}
                            >
                                {item.address}
                            </Text>
                        </View>

                        <Text
                            style={{
                                fontWeight: '400',
                                fontSize: 16,
                                color: '#888888'
                            }}
                        >
                            現時可用充電槍數目: {item.availableConnectors}
                        </Text>
                    </View>
                </View>
            </Pressable>
        );
    };

    return (
        <SafeAreaView edges={['top', 'left', 'right']} className="flex-1 bg-white">
            <ScrollView className="flex-1 mt-8 " nestedScrollEnabled={true} showsVerticalScrollIndicator={false}>
                <View>
                    <View>
                        <Text className="text-5xl pt-1 pb-6 mx-[5%]">暫無正在進行的充電</Text>
                        <View>
                            <Text className="text-lg mx-[5%] mb-6">立刻前往Crazy Charge 充電站充電吧！</Text>

                            <View>
                                {newAvailableConnectors?.map((item, index) => (
                                    <View key={index}>
                                        <View className="border-b border-gray-200" />
                                        <StationRow item={item} key={index}/>
                                    </View>
                                ))}
                            </View>
                        </View>
                    </View>
                </View>
            </ScrollView>
        </SafeAreaView>
    );
};
const styles = StyleSheet.create({
    grayColor: {
        color: '#888888'
    },
    greenColor: {
        color: '#02677D'
    },
    image: {
        width: 100,
        height: 100,
        margin: 15,
        borderRadius: 10
    }
});

export default NoChargingOngoingPageComponent;
