// component/chargingPage/chargingPageComponent.tsx
import { View, Text, ScrollView, StyleSheet, Image, ActivityIndicator } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import RippleEffectBatteryIcon from '../global/rippleEffectBatteryIcon';
import LoadingDots from '../global/loadingDots';
import NormalButton from '../global/normal_button';
import { router } from 'expo-router';
import { BatteryIconSvg, LightingLogoSvg, TemperatureIconSvg } from '../global/SVG';
import { useContext, useEffect, useState } from 'react';
import { chargeStationService } from '../../service/chargeStationService';
import { set } from 'date-fns';
import { convertToHKTime } from '../../util/lib';
import ChargingPenaltyPageComponent from './chargingPenaltyComponent';
import { AuthContext } from '../../context/AuthProvider';
import { useTranslation } from '../../util/hooks/useTranslation';

const ChargingPageComponent = ({ data }) => {
    const { t } = useTranslation();
    const reservationData = Array.isArray(data) ? data[0] : data;
    const [isLoading, setIsLoading] = useState(true);
    const [loading, setLoading] = useState(false);
    const [onGoingChargingData, setOnGoingChargingData] = useState();

    const voltageA = onGoingChargingData?.data?.VoltageA;
    const currentA = onGoingChargingData?.data?.CurrentA;
    const { user } = useContext(AuthContext);
    useEffect(() => {
        const fetchOngoingChargingData = async () => {
            setIsLoading(true);
            try {
                const response = await chargeStationService.fetchOngoingChargingData(reservationData.format_order_id);
                if (response) {
                    setOnGoingChargingData(response);
                
                } else {
                }
            } catch (error) {
                console.error('Error fetching reservation histories:', error);
            } finally {
                setIsLoading(false);
            }
        };
        fetchOngoingChargingData();
    }, [reservationData]);

    const stopPayLoad = {
        StartChargeSeq: reservationData.format_order_id,
        ConnectorID: reservationData.connector.ConnectorID
    };

    const handleStopCharge = async () => {
        setLoading(true);
        try {
            const response = await chargeStationService.stopCharging(stopPayLoad);
            if (response) {
                setLoading(false);
            } else {
                setLoading(false);
            }
        } catch (error) {
            setLoading(false);
        }
    };

    //now i make a reservation, make it a 7 and see if it comes here
    useEffect(() => {
        const now = new Date();
        const endTime = reservationData?.end_time ? new Date(reservationData.end_time) : null;
        const snapshotData = reservationData?.snapshot ? JSON.parse(reservationData.snapshot) : null;

        if (reservationData && snapshotData) {
            const isWalkingOrIcCall = snapshotData.type === 'walking' || snapshotData.is_ic_call === true;
            const shouldStopCharge = reservationData.Soc >= 95 || (!isWalkingOrIcCall && endTime && now >= endTime);

            if (shouldStopCharge) {
                console.log(
                    'Initiating automatic stop. Reason:',
                    reservationData.Soc >= 95 ? 'Battery reached 95% or higher' : 'End time reached'
                );
                handleStopCharge();
            }
        }
    }, [reservationData]);

    //用來計充電歷時
    const [timeSince, setTimeSince] = useState<string>('');

    useEffect(() => {
        const updateTimeSince = () => {
            if (reservationData && reservationData.actual_start_time) {
                setTimeSince(timeSinceBooking(reservationData.actual_start_time) || t('common.calculating'));
            } else {
                setTimeSince(t('common.calculating'));
            }
        };
        updateTimeSince();
        // Update every minute
        const intervalId = setInterval(updateTimeSince, 60000);
        // Cleanup interval on component unmount
        return () => clearInterval(intervalId);
    }, [reservationData]);

    function timeSinceBooking(timeString) {
        if (timeString) {
            // console.log('timeString in timeSinceBooking', timeString);
            const startTime = new Date(timeString);
            const now = new Date();
            // console.log('now in timeSinceBooking', now);
            // console.log('startTime in timeSinceBooking', startTime);
            // console.log('now - startTime', now - startTime);
            const diffInMilliseconds = now - startTime;
            const diffInMinutes = Math.floor(diffInMilliseconds / (1000 * 60));
            // console.log('diffInMinutes in timeSinceBooking', diffInMinutes);
            if (diffInMinutes < 1) {
                return '< 1 minute';
            } else {
                return `${diffInMinutes} minute${diffInMinutes !== 1 ? 's' : ''}`;
            }
        }
    }
    //用來計充電歷時    //用來計充電歷時    //用來計充電歷時    //用來計充電歷時    //用來計充電歷時

    const displayKW = (currentA: number, voltageA: number) => {
        if (currentA && voltageA) {
            return (currentA * voltageA) / 1000;
        } else return 30.0;
    };

    const connectorIDToLabelMap = {
        '101708240502475001': '1',
        '101708240502476001': '2',
        '101708240502477001': '3',
        '101708240502478001': '4',
        '101708240502474001': '5',
        '101708240502474002': '6'
    };

    if (isLoading) {
        return (
            <SafeAreaView style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
                <ActivityIndicator size="large" />
                <Text>{t('common.loading')}</Text>
            </SafeAreaView>
        );
    }

    return (
        <SafeAreaView style={{ flex: 1, backgroundColor: 'white' }} edges={['top', 'left', 'right']}>
            <ScrollView className="flex-1">
                <View className="flex-1 mx-[5%] space-y-4">
                    <View className="items-center">
                        <View className="mt-6 mb-4">
                            <Text className="text-lg ">{t('chargingInfo.currently_charging')}</Text>
                        </View>
                        <Text className="text-4xl font-light">
                            {/* {reservationData.car.car_brand.name} {reservationData.car.car_type.name} */}
                            {user?.nickname}
                        </Text>
                    </View>

                    <View className="items-center">
                        <Text className="text-lg" style={styles.grayColor}>
                            {t('chargingInfo.charging')}
                        </Text>
                        <View className="flex-row space-x-4 p-4 pr-8 items-center justify-center ml-10">
                            <RippleEffectBatteryIcon />
                            <Text
                                style={{
                                    color: '#02677D',
                                    fontSize: 60,
                                    fontWeight: 300
                                }}
                            >
                                {`${reservationData.Soc}%`}
                                {/* {`64%`} */}

                                <LoadingDots />
                            </Text>
                        </View>
                    </View>

                    <View
                        className="h-[220px] min-h-[20px] border-slate-300 rounded-2xl flex-column"
                        style={{ borderWidth: 1 }}
                    >
                        {/* Top */}
                        {/* this is actual total power */}
                        <View className="h-[65%] flex-row justify-evenly items-center">
                            <View className="flex-1 flex-column items-center space-y-2">
                                <LightingLogoSvg />
                                <Text style={styles.grayColor} className="text-base">
                                    {t('chargingInfo.actual_charged_kwh')}
                                </Text>
                                {isLoading ? (
                                    <ActivityIndicator />
                                ) : (
                                    <Text style={styles.greenColor} className="font-bold text-base">
                                        {/* {displayKW(onGoingChargingData.CurrentA, onGoingChargingData.VoltageA)}kW */}
                                        {reservationData.actual_total_power
                                            ? `${reservationData.actual_total_power.toFixed(1)}`
                                            : t('common.calculating')}
                                    </Text>
                                )}
                            </View>

                            <View className="flex-1 flex-column items-center space-y-2">
                                <BatteryIconSvg />
                                <Text style={styles.grayColor} className="text-base">
                                    {t('chargingInfo.actual_power_kw')}
                                </Text>
                                {isLoading ? (
                                    <ActivityIndicator />
                                ) : (
                                    <Text style={styles.greenColor} className="font-bold text-base">
                                        {onGoingChargingData && voltageA && currentA
                                            ? ((voltageA * currentA) / 1000).toFixed(1)
                                            : t('chargingInfo.see_charger_display')}
                                    </Text>
                                )}
                            </View>
                        </View>
                        <View className="mx-[5%]">
                            <View className="h-[1px] w-[100%] bg-[#CCCCCC]" />
                        </View>
                        {/* bottom container */}
                        <View className="h-[35%] mx-[5%] justify-center ">
                            <Text style={styles.grayColor} className="text-base">
                                {t('chargingInfo.charging_duration')} ~{timeSince}
                            </Text>
                        </View>
                    </View>
                    <View className="border-slate-300 rounded-2xl justify-center p-4" style={{ borderWidth: 1 }}>
                        <Text className="text-lg pb-1 ">{t('chargingInfo.other_info')}</Text>
                        <View className="flex-row">
                            <View className="flex-1 flex-column">
                                <Text className="text-base" style={styles.grayColor}>
                                    {t('chargingInfo.start_time')}
                                </Text>
                                <Text className="text-base">
                                    {convertToHKTime(reservationData.actual_start_time).hkTime.slice(0, 5)}
                                </Text>
                            </View>
                            <View className="flex-1 flex-column">
                                <Text className="text-base" style={styles.grayColor}>
                                    {t('chargingInfo.charger')}
                                </Text>
                                <Text className="text-base">
                                    {t('chargingInfo.charger_number', { number: connectorIDToLabelMap[reservationData.connector.ConnectorID] })}
                                </Text>
                            </View>
                        </View>
                    </View>

                    <View>
                        <NormalButton
                            onPress={() => {
                                router.push('mainPage');
                            }}
                            title={
                                <Text className="text-xl text-white" style={{ fontWeight: 900 }}>
                                    {t('chargingInfo.return_home')}
                                </Text>
                            }
                        />
                    </View>
                </View>
            </ScrollView>
        </SafeAreaView>
    );
};

export default ChargingPageComponent;
const styles = StyleSheet.create({
    grayColor: {
        color: '#888888'
    },
    greenColor: {
        color: '#02677D'
    },
    text: {
        fontWeight: 300,
        color: '#000000'
    }
});