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 } from 'expo-router';
import { 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 = () => {
    //fetch charge station info
    const [chargeStationInfo, setChargeStationInfo] = useState([]);
    const [availableConnectors, setAvailableConnectors] = useState({});
    useEffect(() => {
        const fetchChargeStationInfo = async () => {
            try {
                const chargeStationInfo = await chargeStationService.fetchAllChargeStations();
                console.log('chargeStationInfo in noChargingOngoingPageComponent', chargeStationInfo);
                const onlyWaiYipStreetStation = chargeStationInfo.filter(
                    (station) => station.id == '2405311022116801000'
                );
                setChargeStationInfo(onlyWaiYipStreetStation);

                // setChargeStationInfo(chargeStationInfo);
            } catch (error) {
                console.error('Error fetching charge station info:', error);
            }
        };
        fetchChargeStationInfo();
    }, []);

    const fetchConnectorWithRetry = async (stationId, retryCount = 0) => {
        try {
            const response = await chargeStationService.fetchAvailableConnectors(stationId);
            if (response === 500 || !response) {
                throw new Error('Server error');
            }
            return response;
        } catch (error) {
            if (retryCount < MAX_RETRIES) {
                console.log(`Retrying fetch for station ${stationId}, attempt ${retryCount + 1}`);
                await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY));
                return fetchConnectorWithRetry(stationId, retryCount + 1);
            }
            console.error(`Failed to fetch connectors for station ${stationId} after ${MAX_RETRIES} attempts:`, error);
            return null;
        }
    };

    useEffect(() => {
        const fetchAllConnectors = async () => {
            try {
                const connectorData = {};
                for (const station of chargeStationInfo) {
                    const stationConnectors = await fetchConnectorWithRetry(station.id);
                    if (stationConnectors !== null) {
                        connectorData[station.id] = stationConnectors;
                        // Update state immediately for each successful fetch
                        setAvailableConnectors((prev) => ({
                            ...prev,
                            [station.id]: stationConnectors
                        }));
                    }
                }
            } catch (error) {
                console.error('Error fetching connectors:', error);
            }
        };

        if (chargeStationInfo.length > 0) {
            fetchAllConnectors();
        }
    }, [chargeStationInfo]);

    const StationRow = ({ item }) => (
        <Pressable
            onPress={() => {
                router.push({
                    pathname: '/resultDetailPage',
                    params: {
                        chargeStationAddress: item.snapshot.Address,
                        chargeStationID: item.id,
                        chargeStationName: item.snapshot.StationName,
                        availableConnectors: availableConnectors[item.id]
                    }
                });
            }}
        >
            <View className="flex flex-1 flex-row w-full ">
                <Image style={styles.image} source={require('../../assets/dummyStationPicture.png')} />
                <View className="flex flex-col gap-2 mt-5 mr-2">
                    <Text
                        style={{
                            fontWeight: '700',
                            color: '#02677D',
                            fontSize: 20
                        }}
                    >
                        {item.snapshot.StationName}
                    </Text>
                    <View className="flex flex-row justify-between space-x-2">
                        <Text
                            style={{
                                fontWeight: '400',
                                fontSize: 16,
                                color: '#222222'
                            }}
                        >
                            {item.snapshot.Address}
                        </Text>
                        {/* <Text
                            style={{
                                fontWeight: '400',
                                fontSize: 16,
                                color: '#222222'
                            }}
                        >
                            已付金額:{' '}
                            {item.actual_fee
                                ? item.actual_fee % 1 === 0
                                    ? `$${item.actual_fee}`
                                    : `$${item.actual_fee.toFixed(1)}`
                                : ''}
                        </Text> */}
                    </View>
                    {!availableConnectors[item.id] && (
                        <Text
                            style={{
                                fontWeight: '400',
                                fontSize: 16,
                                color: '#888888'
                            }}
                        >
                            正在查詢可用充電槍數目...
                        </Text>
                    )}
                    {availableConnectors[item.id] && (
                        <Text
                            style={{
                                fontWeight: '400',
                                fontSize: 16,
                                color: '#888888'
                            }}
                        >
                            現時可用充電槍數目: {availableConnectors[item.id]}
                        </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 className="">
                    <View className="">
                        <Text className="text-5xl pt-1 pb-6 mx-[5%]">暫無正在進行的充電</Text>
                        <View>
                            <Text className="text-lg mx-[5%] mb-6">立刻前往Crazy Charge 充電站充電吧！</Text>

                            <View className="">
                                {chargeStationInfo?.map((item, index) => (
                                    <View key={index}>
                                        <View className=" border-b border-gray-200" />
                                        <StationRow item={item} key={index} />
                                    </View>
                                ))}
                                {/* <NormalButton
                                    title={<Text className="text-white text-lg">前往預約頁面</Text>}
                                    onPress={() => router.push('/bookingMenuPage')}
                                /> */}
                            </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;
// const styles = StyleSheet.create({
//     container: {
//         flexDirection: 'row',
//         width: '100%',
//         flex: 1
//     },

//     textContainer: {
//         flex: 1,
//         flexDirection: 'column',
//         gap: 8,
//         marginTop: 20,
//         marginRight: 8 // Add right margin to prevent text from touching the edge
//     }
// });
