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';
import { useTranslation } from '../../util/hooks/useTranslation';
// const RETRY_DELAY = 2000; // 2 seconds
// const MAX_RETRIES = 3; // Maximum number of retry attempts

const NoChargingOngoingPageComponent = () => {
    const { t } = useTranslation(); // 使用翻译钩子
    const [newAvailableConnectors, setNewAvailableConnectors] = useState<any>([]);
    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: Record<string, number> = {
                                '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 }: { item: any }) => {
        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: item.image,
                            stationLng: item.stationLng,
                            stationLat: item.stationLat,
                            pricemodel_id: item.pricemodel_id
                        }
                    });
                }}
            >
                <View className="flex flex-1 flex-row w-full ">
                <Image style={styles.image} source={imgObj} />
                <View className="flex flex-col gap-2 mt-5 mr-2 flex-1">
                    <Text
                        style={{
                            fontWeight: '700',
                            color: '#02677D',
                            fontSize: 20,
                            flexWrap: 'wrap',
                            flexShrink: 1
                        }}
                        numberOfLines={0}
                    >
                        {item.stationName}
                    </Text>
                    <View className="flex flex-row justify-between space-x-2">
                        <Text
                            style={{
                                fontWeight: '400',
                                fontSize: 16,
                                color: '#222222',
                                flexWrap: 'wrap',
                                flexShrink: 1
                            }}
                            numberOfLines={0}
                        >
                            {item.address}
                        </Text>
                    </View>

                    <Text
                        style={{
                            fontWeight: '400',
                            fontSize: 16,
                            color: '#888888',
                            flexWrap: 'wrap',
                            flexShrink: 1
                        }}
                        numberOfLines={0}
                    >
                        {t('charging.no_ongoing.available_connectors')}: {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%]">{t('charging.no_ongoing.title')}</Text>
                        <View>
                            <Text className="text-lg mx-[5%] mb-6">{t('charging.no_ongoing.subtitle')}</Text>

                            <View>
                                {newAvailableConnectors?.map((item: any, index: number) => (
                                    <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;