import { View, Text, ActivityIndicator, AppState, ScrollView, RefreshControl } from 'react-native';
import React, { useCallback, useContext, useEffect, useRef, useState } from 'react';
import ChargingPageComponent from '../../../../component/chargingPage/chargingPageComponent';
import { chargeStationService } from '../../../../service/chargeStationService';
import ChargingPenaltyPageComponent from '../../../../component/chargingPage/chargingPenaltyComponent';
import NoChargingOngoingPageComponent from '../../../../component/chargingPage/noChargingOngoingPageComponent';
import { useFocusEffect } from 'expo-router';
import ChargingHurryUpPageComponent from '../../../../component/chargingPage/chargingHurryUpPageComponent';
import FutureReservationPageComponent from '../../../../component/chargingPage/futureReservationPageComponent';
import ChargingFinishPageComponent from '../../../../component/chargingPage/chargingFinishPageComponent';
import { AuthContext } from '../../../../context/AuthProvider';

//***********************************************************************
//而家start time & end time 一樣就當Walk in, walkin 會改左d字眼在ChargingHurryUpPageComponent
//如果以後scan qr code可選時間， ChargingHurryUp display 字眼個logic 就要改
//***********************************************************************
const ChargingPage = () => {
    const [data, setData] = useState();
    const [isLoading, setIsLoading] = useState(false);
    const [currentStatus, setCurrentStatus] = useState('');
    const intervalRef = useRef(null);
    const lastUpdateTimeRef = useRef(Date.now());
    const { user } = useContext(AuthContext);
    const [refreshing, setRefreshing] = useState(false);
    const [refetchTrigger, setRefetchTrigger] = useState(0);

    const fetchReservationData = useCallback(async () => {
        setIsLoading(true);
        try {
            const now = new Date();
            const response = await chargeStationService.fetchReservationHistories();
            lastUpdateTimeRef.current = Date.now();

            if (Object.keys(response).length === 0) {
                setCurrentStatus('noReservation');
            } else {
                // Check for recently finished reservations
                const finishedReservation = response.find((r) => {
                    if (r.status.id === '8' && r.actual_end_time) {
                        const endTime = new Date(r.actual_end_time);
                        const timeDifference = now.getTime() - endTime.getTime();
                        return timeDifference <= 1 * 60 * 1000; // Within 1 minutes
                    }

                    return false;
                });
                if (finishedReservation) {
                    setCurrentStatus('finishReservation');
                    setData(finishedReservation);
                } else {
                    // Existing checks for other reservation types
                    const penaltyReservation = response.filter(
                        (r) => r.actual_start_time != null && r.actual_end_time != null && r.connector.Status === 7
                    );
                    if (penaltyReservation.length > 0) {
                        setCurrentStatus('penaltyReservation');
                        setData(penaltyReservation);
                    } else {
                        // Check for ongoing reservations (已插槍的預約)
                        const onGoingReservation = response.filter(
                            (r) => r.status.id === '7' && r.actual_end_time == null
                        );
                        if (onGoingReservation.length > 0) {
                            setCurrentStatus('onGoingReservation');
                            setData(onGoingReservation);
                        } else {
                            // Check for recently passed reservations (仍未開始插槍充電的預約)
                            const recentlyPassedReservations = response.filter((r) => {
                                const bookTime = new Date(r.book_time);
                                const fifteenMinutesAfterBookTime = new Date(bookTime.getTime() + 15 * 60 * 1000);
                                const isWithin15MinutesAndStatus6 =
                                    now > bookTime && now <= fifteenMinutesAfterBookTime && r.status.id === '6';
                                return isWithin15MinutesAndStatus6;
                            });
                            if (recentlyPassedReservations.length > 0) {
                                setCurrentStatus('recentlyPassedReservations');
                                setData(recentlyPassedReservations);
                            } else {
                                const futureReservation = response.filter((r) => {
                                    const bookTime = new Date(r.book_time);
                                    const fifteenMinutesAfterBookTime = new Date(bookTime.getTime() + 15 * 60 * 1000);
                                    return now < bookTime || (now > bookTime && now <= fifteenMinutesAfterBookTime);
                                });
                                if (futureReservation.length > 0) {
                                    futureReservation.sort((a, b) => new Date(a.end_time) - new Date(b.end_time));
                                    const closestReservation = futureReservation[0];
                                    setCurrentStatus('futureReservation');
                                    setData(closestReservation);
                                } else {
                                    //if you are here, it means there are no future reservations (but there are past reservations)
                                    setCurrentStatus('noReservation');
                                }
                            }
                        }
                    }
                }
            }
        } catch (error) {
            console.log('Error fetching reservation histordfsdfes:', error);
        } finally {
            setIsLoading(false);
        }
    }, []);

    const onRefresh = useCallback(() => {
        setRefreshing(true);
        setRefetchTrigger((prev) => prev + 1);
        // Simulate a delay to show the refresh indicator
        setTimeout(() => {
            setRefreshing(false);
            fetchReservationData().finally(() => {
                setRefreshing(false);
            });
        }, 1000);
    }, []);

    const checkAndUpdateData = useCallback(() => {
        const currentTime = Date.now();
        const timeSinceLastUpdate = currentTime - lastUpdateTimeRef.current;
        if (timeSinceLastUpdate > 60000) {
            // If more than a minute has passed
            fetchReservationData();
        }
    }, [fetchReservationData]);

    useEffect(() => {
        const subscription = AppState.addEventListener('change', (nextAppState) => {
            if (nextAppState === 'active') {
                checkAndUpdateData();
            }
        });

        return () => {
            subscription.remove();
        };
    }, [checkAndUpdateData]);

    useEffect(() => {
        fetchReservationData();
        intervalRef.current = setInterval(fetchReservationData, 60000);

        return () => {
            if (intervalRef.current) {
                clearInterval(intervalRef.current);
            }
        };
    }, [fetchReservationData]);

    useFocusEffect(
        useCallback(() => {
            let isActive = true;

            const fetchData = async () => {
                try {
                    await fetchReservationData();
                } catch (error) {
                    console.error('Error in useFocusEffect:', error);
                }
            };
            fetchData();
            // Cleanup function
            return () => {
                isActive = false;
                // Any additional cleanup logic can go here
            };
        }, [fetchReservationData])
    );

    if (isLoading) {
        return (
            <View className="flex-1 justify-center bg-white">
                <ActivityIndicator color="#34657b" size="large" />
            </View>
        );
    }

    return (
        <ScrollView
            className="bg-white flex-1"
            refreshControl={
                <RefreshControl
                    refreshing={refreshing}
                    onRefresh={onRefresh}
                    colors={['#34657b']} // Android
                    tintColor="#34657b" // iOS
                />
            }
        >
            <View className="flex-1">
                {currentStatus === 'noReservation' && <NoChargingOngoingPageComponent />}
                {currentStatus === 'penaltyReservation' && <ChargingPenaltyPageComponent data={data} />}
                {currentStatus === 'onGoingReservation' && <ChargingPageComponent data={data} />}
                {currentStatus === 'recentlyPassedReservations' && <ChargingHurryUpPageComponent data={data} />}
                {currentStatus === 'futureReservation' && <FutureReservationPageComponent data={data} />}
                {currentStatus === 'finishReservation' && <ChargingFinishPageComponent data={data} />}
            </View>
        </ScrollView>
    );
};

export default ChargingPage;
