import { View, Text, ScrollView, Pressable, StyleSheet, Alert } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { router, useLocalSearchParams, useNavigation } from 'expo-router';
import NormalButton from '../global/normal_button';
import { useEffect, useState } from 'react';
import { chargeStationService } from '../../service/chargeStationService';
import useUserInfoStore from '../../providers/userinfo_store';
import { PreviousPageBlackSvg } from '../global/SVG';

const PenaltyPaymentPageComponent = () => {
    const params = useLocalSearchParams();
    const { userID } = useUserInfoStore();
    const navigation = useNavigation();
    const [leaving_time, setLeavingTime] = useState<string | null>(null)
    useEffect(() => {
        navigation.setOptions({
            gestureEnabled: false
        });
    }, [navigation]);
    useEffect(() => {
        chargeStationService.fetchChargingDetails(params.id.toString()).then(res => {
          if (res && res[0].charging.length > 0) {
            const { date, time } = convertBookingDateTime(res[0].charging[0].leaving_time as string);
            setLeavingTime(time);
          }
        })
    }, [params]);
    const convertBookingDateTime = (isoDateString: string): { date: string; time: string } => {
        const bookingDate = new Date(isoDateString);

        // Adjust to local time (+8 hours)
        bookingDate.setHours(bookingDate.getHours());

        // Format date as "MM-DD"
        const date = `${(bookingDate.getMonth() + 1).toString().padStart(2, '0')}-${bookingDate
            .getDate()
            .toString()
            .padStart(2, '0')}`;

        // Format time as "HH:mm"
        const time = `${bookingDate.getHours().toString().padStart(2, '0')}:${bookingDate
            .getMinutes()
            .toString()
            .padStart(2, '0')}`;

        return { date, time };
    };

    const calculateUserEndTime = (actualEndTimeStr: string, penaltyFee: string): string => {
        const actualEndTime = new Date(actualEndTimeStr);
        const penaltyMinutes = Math.floor(parseFloat(penaltyFee) / 3) + 15 // $3 per minute
        const userEndTime = new Date(actualEndTime.getTime() + penaltyMinutes * 60000); // add minutes

        return userEndTime.toISOString();
    };

    const { date, time } = convertBookingDateTime(params.book_time as string);
    const { date: actual_end_date, time: actual_end_time } = convertBookingDateTime(params.actual_end_time as string);
    const { time: user_end_time } = convertBookingDateTime(
        calculateUserEndTime(params.actual_end_time as string, params.penalty_fee as string)
    );

    const payload = {
        userId: userID,
        amount: parseFloat(params.penalty_fee as string),
        reservationId: params.id
    };

    const handlePayment = async () => {
        try {
            const result = await chargeStationService.payPenalty(payload);
            console.log('Payment result:', result);
            if (result.status) {
                Alert.alert('支付成功', '罰款已成功支付', [
                    { text: '確認', onPress: () => router.replace('/mainPage') }
                ]);
            } else {
                Alert.alert('支付失敗', '餘額不足，即將跳轉到錢包', [
                    { text: '確認', onPress: () => router.push('/(account)/(wallet)/walletPage') }
                ]);
            }
        } catch (error) {
            console.error('Payment error:', error);
            Alert.alert('支付錯誤', '發生錯誤，請稍後再試');
        }
    };

    return (
        <SafeAreaView style={{ flex: 1, backgroundColor: 'white' }} edges={['top', 'left', 'right']}>
            <ScrollView className="flex-1" showsVerticalScrollIndicator={false}>
                <View style={{ marginTop: 25 }} className="mx-[5%]">
                    <Pressable
                        onPress={() => {
                            if (router.canGoBack()) {
                                router.back();
                            } else {
                                router.replace('/mainPage');
                            }
                        }}
                    >
                        <PreviousPageBlackSvg />
                    </Pressable>
                    <Text className="text-3xl my-8 text-center">尚未繳付罰款的充電記錄</Text>
                </View>

                <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">
                                {actual_end_time}
                            </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">
                                {leaving_time || user_end_time}
                            </Text>
                        </View>
                    </View>
                    <View className="flex-1 flex-column justify-center space-y-1 pb-3">
                        <Text style={styles.grayColor} className="text-base">
                            充電日期
                        </Text>
                        <Text style={styles.greenColor} className="text-base">
                            {date}
                        </Text>
                    </View>
                    {/* <View className="flex-1 flex-column justify-center space-y-1 pb-3">
                        <Text style={styles.grayColor} className="text-base">
                            充電地點
                        </Text>
                        <Text style={styles.greenColor} className="text-base ">
                            Crazy Charge(偉業街)
                        </Text>
                    </View> */}
                    <View className="flex-1 flex-column justify-center space-y-1 pb-3">
                        <Text style={styles.grayColor} className="text-base">
                            罰款金額
                        </Text>
                        <Text style={styles.greenColor} className="text-lg ">
                            {params.penalty_fee}
                        </Text>
                    </View>
                    <View className="flex-1 flex-column justify-center space-y-1 pb-3">
                        <Text style={styles.grayColor} className="text-base">
                            訂單編號
                        </Text>
                        <Text style={styles.greenColor} className=" ">
                            {params.format_order_id}
                        </Text>
                    </View>
                </View>

                <View className="border-t mx-4 border-[#CCCCCC]"></View>
                <View className="flex-1 mx-[5%] mt-4 space-y-1">
                    <View className="mt-4">
                        <NormalButton
                            title={
                                <Text
                                    style={{
                                        color: 'white',
                                        fontSize: 16,
                                        fontWeight: '800'
                                    }}
                                >
                                    支付罰款
                                </Text>
                            }
                            // onPress={handlePayment}
                            onPress={() => {
                                Alert.alert('將會從錢包餘額扣除款項以繳交罰款', '', [
                                    { text: '取消', style: 'cancel' },
                                    { text: '確認', onPress: handlePayment }
                                ]);
                            }}
                            extendedStyle={{ padding: 24, marginTop: 24 }}
                        />
                    </View>
                </View>
            </ScrollView>
        </SafeAreaView>
    );
};

export default PenaltyPaymentPageComponent;

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