import { View, Text, ScrollView, StyleSheet, Pressable } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Alert } from 'react-native';

import NormalButton from '../global/normal_button';
import { router, useLocalSearchParams } from 'expo-router';
import { GrayRightArrowIconSvg, RightArrowIconSvg, TickLogoSvg } from '../global/SVG';
import { useEffect, useRef, useState } from 'react';
import useBookingStore from '../../providers/booking_store';
import useCouponStore from '../../providers/coupon_store';
import { walletService } from '../../service/walletService';

const PaymentSummaryPageComponent = () => {
    const selectedCouponName = useCouponStore((state) => state.selectedCouponName);
    const selectedCouponRedeemCode = useCouponStore((state) => state.selectedCouponRedeemCode);

    const selectedCouponPrice = useCouponStore((state) => state.selectedCouponPrice);
    const params = useLocalSearchParams();
    const setBookingInfo = useBookingStore((state) => state.setBookingInfo);
    const initialSetupDone = useRef(false);
    const [formatOrderId, setFormatOrderId] = useState('');
    useEffect(() => {
        if (!initialSetupDone.current && Object.keys(params).length > 0) {
            const bookingInfo = {
                bookTime: params.bookTime,
                date: params.date,
                carID: params.carID as string,
                chargingWatt: params.chargingWatt as string,
                connectorID: params.connectorID as string,
                price: params.price as string,
                stationID: params.stationID as string,
                user: params.userID as string,
                paymentFee: params.paymentFee as string,
                carCapacitance: params.carCapacitance as string
            };
            setBookingInfo(bookingInfo);
            console.log('Booking info stored:', bookingInfo);
            initialSetupDone.current = true;
        }
    }, [params, setBookingInfo]);

    const { bookTime, date, carID, chargingWatt, connectorID, price, stationID, user, paymentFee, carCapacitance } =
        useBookingStore();

    const calculateFinalFee = (): string => {
        console.log('selected coupon price:', selectedCouponPrice);
        if (selectedCouponRedeemCode && selectedCouponPrice) {
            const difference = parseFloat(paymentFee) - parseFloat(selectedCouponPrice);
            return Math.max(0, difference).toFixed(2);
        } else {
            return paymentFee;
        }
    };

    const finalFee = calculateFinalFee();
    const total_power = chargingWatt === '' ? carCapacitance : parseFloat(chargingWatt.split('~')[0]);

    const promotion_code = selectedCouponRedeemCode || '';

    const convertEndTime = (num1: number) => {
        switch (num1) {
            case 20:
                return 25;
            case 25:
                return 30;
            case 30:
                return 40;
            case 40:
                return 45;
        }
    };

    function convertToUTC(date, bookTime) {
        const currentYear = new Date().getFullYear();
        const [month, day] = date.split('/');
        const fullDate = new Date(`${currentYear}-${month}-${day}T${bookTime}:00`);
        fullDate.setHours(fullDate.getHours());
        return fullDate;
    }

    const book_time = convertToUTC(date, bookTime);
    const timeRequiredInMinute = convertEndTime(Number(chargingWatt.split(' ')[0]));

    function findEndTime(num1, book_time) {
        const date = new Date(book_time);
        date.setMinutes(date.getMinutes() + num1);
        return date;
    }

    let end_time;
    if (chargingWatt === '') {
        end_time = book_time;
    } else {
        const endingTime = findEndTime(timeRequiredInMinute, book_time);
        end_time = endingTime;
    }

    const handleSubmitPayment = async () => {
        let type = 'reservation';
        let is_ic_call = false;
        console.log('i am handleSubmitPayment, connectorID:', connectorID);

        try {
            const response = await walletService.submitPayment(
                stationID,
                connectorID,
                user,
                book_time,
                end_time,
                total_power,
                total_fee,
                promotion_code,
                carID,
                type,
                is_ic_call
            );
            if (response.status === 200 || response.status === 201) {
                console.log('submit payment successful');

                // router.push('/paymentFinishPage');
                router.push({
                    pathname: '/paymentFinishPage',
                    params: { formatOrderId: response.data.format_order_id }
                });
            } else if (response.status === 400) {
                console.log('400 error in paymentSummaryPageComponent');
                Alert.alert('餘額不足', '您的餘額不足，請充值後再試。');
            } else {
                console.log('submit payment failed:', response.status);
            }
        } catch (error) {
            console.log('submit payment error:', error);
        }
    };

    const total_fee = parseInt(finalFee, 10);

    // console.log(' i am only console.log all variables for clarity:', {
    //     stationID,
    //     connectorID,
    //     user,
    //     book_time,
    //     end_time,
    //     total_power,
    //     total_fee,
    //     promotion_code,
    //     carID
    // });

    return (
        <SafeAreaView className="flex-1 bg-white" edges={['top', 'left', 'right']}>
            <ScrollView className="flex-1 mx-[5%]" showsVerticalScrollIndicator={false}>
                <View style={{ marginTop: 25 }}>
                    <Text style={{ fontSize: 45, paddingBottom: 12 }}>付款概要</Text>
                    <View className="flex-column">
                        <Pressable onPress={() => router.push('selectCouponPage')}>
                            <Text className="text-lg pb-4">優惠券</Text>
                            {selectedCouponName === '' ? (
                                <View
                                    style={{
                                        borderWidth: 1,
                                        padding: 20,
                                        borderRadius: 12,
                                        borderColor: '#bbbbbb'
                                    }}
                                    className="rounded-xl h-[9vh] items-center flex-row pl-6 justify-between"
                                >
                                    <View className="flex-row items-center ">
                                        <Text className="color-[#999999] px-4 text-base">選擇優惠券</Text>
                                    </View>
                                    <View className="pr-4">
                                        <GrayRightArrowIconSvg />
                                    </View>
                                </View>
                            ) : (
                                <View className="bg-[#e9f2f7] rounded-xl h-[9vh] items-center flex-row pl-6 justify-between">
                                    <View className="flex-row items-center ">
                                        <TickLogoSvg />
                                        <Text className="color-[#34667c] px-4 text-base">{selectedCouponName}</Text>
                                    </View>
                                    <View className="pr-4">
                                        <RightArrowIconSvg />
                                    </View>
                                </View>
                            )}
                        </Pressable>
                    </View>

                    <View>
                        <Text className="text-xl py-4">收費概要</Text>
                        <View className="flex-row justify-between">
                            <Text className="text-base">充電費用</Text>
                            <Text className="text-base">HK ${finalFee}</Text>
                        </View>

                        {chargingWatt === '' ? (
                            <Text style={styles.grayColor} className="text-base">
                                充滿停機預估費用
                            </Text>
                        ) : (
                            <Text style={styles.grayColor} className="text-base">
                                按每度電結算:
                                {chargingWatt?.split('~')[0]}
                            </Text>
                        )}

                        <View className="h-0.5 my-3 bg-[#f4f4f4]" />
                        <View className="flex-row justify-between ">
                            <Text className="text-xl">總計</Text>
                            <Text className="text-3xl">
                                HK$
                                {finalFee}
                            </Text>
                        </View>
                        <View className="mt-4 ">
                            <NormalButton
                                title={
                                    <Text
                                        style={{
                                            color: 'white',
                                            fontSize: 16,
                                            fontWeight: '800'
                                        }}
                                    >
                                        前往付款
                                    </Text>
                                }
                                onPress={
                                    // () => router.push('/paymentFinishPage')
                                    handleSubmitPayment
                                }
                                extendedStyle={{ padding: 24 }}
                            />
                        </View>
                        <View className="h-8" />
                    </View>
                </View>
            </ScrollView>
        </SafeAreaView>
    );
};

export default PaymentSummaryPageComponent;

const styles = StyleSheet.create({
    grayColor: {
        color: '#888888'
    },
    greenColor: {
        color: '#02677D'
    }
});
