import { View, Text, ScrollView, StyleSheet, ActivityIndicator, Alert, Modal } from 'react-native';
import React, { useEffect, useState } from 'react';
import { SafeAreaView } from 'react-native-safe-area-context';
import NormalButton from '../global/normal_button';
import { router } from 'expo-router';
import { chargeStationService } from '../../service/chargeStationService';
import { format, addHours } from 'date-fns';
import { toZonedTime } from 'date-fns-tz';
import { convertToHKTime } from '../../util/lib';

const ChargingHurryUpPageComponent = ({ data = {} }) => {
    // ***************************************************************
    // 2 整個useEffect listen to data. 有新data就轉頁
    // ***************************************************************

    const reservationData = Array.isArray(data) ? data[0] : data;

    const [stationInfo, setStationInfo] = useState(null);
    const [loading, setLoading] = useState(false);
    const [isLoading, setIsLoading] = useState(false);
    const plan = reservationData.book_time === reservationData.end_time ? '充滿停機' : '按每度電結算';
    const kwh = reservationData.total_power === null ? '' : `${reservationData.total_power} kWh`;
    const walkinStatus = reservationData.book_time === reservationData.end_time ? true : false;

    useEffect(() => {
        setLoading(true);
        if (
            reservationData &&
            reservationData.connector &&
            reservationData.connector.EquipmentID &&
            reservationData.connector.EquipmentID.StationID
        ) {
            try {
                const parsedSnapshot = JSON.parse(reservationData.connector.EquipmentID.StationID.snapshot);
                setStationInfo(parsedSnapshot);
            } catch (error) {
                console.error('Error parsing station snapshot:', error);
            }
        }
        setLoading(false);
    }, [reservationData]);

    const startPayload = {
        StartChargeSeq: reservationData.format_order_id,
        ConnectorID: reservationData.connector.ConnectorID,
        StopBy: 0,
        StopValue: 0,
        StartBalance: 400.99
    };

    const handleStartCharge = async () => {
        setIsLoading(true);
        try {
            console.log('startPayload', startPayload);
            const response = await chargeStationService.startCharging(startPayload);
            if (response) {
                console.log('handleStartCharge begins, response received:', response);
                setIsLoading(false);
                Alert.alert('啟動成功', '請稍後等待頁面自動跳轉至充電介面', [{ text: 'OK', onPress: () => {} }]);
                setTimeout(() => {
                    router.push('chargingPage');
                }, 15000);
            } else {
                setIsLoading(false);
                Alert.alert('啟動失敗');
                console.log('啟動失敗');
            }
        } catch (error) {
            setIsLoading(false);
            console.log(error);
            Alert.alert('發生錯誤', '請稍後再試');
        }
    };

    return (
        <SafeAreaView edges={['top', 'left', 'right']} className="flex-1 bg-white">
            <ScrollView className="flex-1 mt-8 " nestedScrollEnabled={true} showsVerticalScrollIndicator={false}>
                <View className="mx-[5%]">
                    <View className="">
                        <Text className="text-5xl pt-1 pb-6">{walkinStatus ? '掃描成功' : '預約已經開始'}</Text>
                        <Text className="text-base">
                            {walkinStatus
                                ? '請按下方按鈕啟動充電槍，當充電槍啟動成功後會自動跳轉至充電介面。'
                                : '到達充電站後，按下方按鈕開始充電。'}
                        </Text>
                        {loading ? (
                            <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
                                <ActivityIndicator color="#34657b" />
                            </View>
                        ) : (
                            <>
                                <Text className="text-2xl py-4 ">
                                    {walkinStatus ? '你的充電資訊為:' : '你的預約為:'}
                                </Text>
                                <View className="border-gray-200 border rounded-md">
                                    <View className="flex-1 mt-4 mx-[5%] ">
                                        <View className="flex-1 flex-row items-center pb-3">
                                            <View className="flex-1 flex-column">
                                                <Text style={styles.grayColor} className="text-base">
                                                    日期
                                                </Text>
                                                <Text style={styles.greenColor} className="text-4xl text-center  pt-2">
                                                    {convertToHKTime(reservationData.book_time)
                                                        .hkDate.split('/')
                                                        .reverse()
                                                        .slice(1)
                                                        .join('月')}
                                                </Text>
                                            </View>
                                            <View className="flex-1 flex-column">
                                                <Text style={styles.grayColor} className="text-base pl-7">
                                                    時間
                                                </Text>
                                                <Text style={styles.greenColor} className="text-4xl text-center pt-2">
                                                    {convertToHKTime(reservationData.book_time).hkTime.slice(0, 5)}
                                                </Text>
                                            </View>
                                        </View>
                                        <View className="flex-1 flex-column justify-center space-y-1 pb-3">
                                            <Text style={styles.grayColor} className="text-base">
                                                充電地點
                                            </Text>
                                            {loading ? (
                                                <ActivityIndicator size="small" />
                                            ) : (
                                                <>
                                                    <Text style={styles.greenColor} className="text-2xl ">
                                                        {stationInfo?.StationName || 'N/A'}
                                                    </Text>
                                                    <Text style={styles.grayColor} className="text-sm">
                                                        {stationInfo?.Address || 'N/A'}
                                                    </Text>
                                                </>
                                            )}
                                        </View>
                                        <View className="flex-1 flex-row  pb-3  ">
                                            <View className="flex-column flex-1">
                                                <Text style={styles.grayColor} className="text-base">
                                                    方案
                                                </Text>

                                                <Text style={styles.greenColor} className="text-lg">
                                                    {plan}
                                                </Text>
                                                <Text style={styles.grayColor} className="text-sm">
                                                    {kwh}
                                                </Text>
                                            </View>
                                            <View className="flex-column flex-1">
                                                <Text style={styles.grayColor} className="text-base">
                                                    車輛
                                                </Text>
                                                <Text style={styles.greenColor} className="text-lg">
                                                    {reservationData.car.car_brand.name}
                                                </Text>
                                                <Text style={styles.greenColor} className="text-lg">
                                                    {reservationData.car.car_type.name}
                                                </Text>
                                            </View>
                                        </View>
                                    </View>
                                </View>
                                <View className="pt-6">
                                    <NormalButton
                                        title={<Text className="text-white text-lg">發動充電樁 - 開始充電</Text>}
                                        onPress={() => handleStartCharge()}
                                    />
                                </View>
                                <View className="pt-6">
                                    <NormalButton
                                        title={<Text className="text-white text-lg">返回主頁</Text>}
                                        onPress={() => router.push('mainPage')}
                                    />
                                </View>
                            </>
                        )}
                    </View>
                </View>
            </ScrollView>
            <Modal transparent={true} animationType="fade" visible={isLoading} onRequestClose={() => {}}>
                <View
                    style={{
                        flex: 1,
                        justifyContent: 'center',
                        alignItems: 'center',
                        backgroundColor: 'rgba(0,0,0,0.5)'
                    }}
                >
                    <View style={{ backgroundColor: 'white', padding: 20, borderRadius: 10, alignItems: 'center' }}>
                        <ActivityIndicator />
                        <Text style={{ marginTop: 10 }}>正在啟動充電...</Text>
                    </View>
                </View>
            </Modal>
        </SafeAreaView>
    );
};
const styles = StyleSheet.create({
    grayColor: {
        color: '#888888'
    },
    greenColor: {
        color: '#02677D'
    }
});

export default ChargingHurryUpPageComponent;
