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';
import { useTranslation } from '../../util/hooks/useTranslation';

const PenaltyPaymentPageComponent = () => {
    const params = useLocalSearchParams();
    const { userID } = useUserInfoStore();
    const navigation = useNavigation();
    const [leaving_time, setLeavingTime] = useState<string | null>(null)
    const { t } = useTranslation();

    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(t('penalty_payment.payment_success'), t('penalty_payment.penalty_paid'), [
                    { text: t('common.confirm'), onPress: () => router.replace('/mainPage') }
                ]);
            } else {
                Alert.alert(t('penalty_payment.payment_failed'), t('penalty_payment.insufficient_balance'), [
                    { text: t('common.confirm'), onPress: () => router.push('/(account)/(wallet)/walletPage') }
                ]);
            }
        } catch (error) {
            console.error('Payment error:', error);
            Alert.alert(t('common.error'), t('penalty_payment.payment_error'));
        }
    };

    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">{t('penalty_payment.unpaid_penalty_title')}</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">
                                {t('penalty_payment.actual_end_time')}
                            </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">
                                {t('penalty_payment.actual_charging_end_time')}
                            </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">
                            {t('penalty_payment.charging_date')}
                        </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">
                            {t('penalty_payment.charging_location')}
                        </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">
                            {t('penalty_payment.penalty_amount')}
                        </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">
                            {t('penalty_payment.order_number')}
                        </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'
                                    }}
                                >
                                    {t('penalty_payment.pay_penalty')}
                                </Text>
                            }
                            // onPress={handlePayment}
                            onPress={() => {
                                Alert.alert(
                                    t('penalty_payment.payment_confirmation'), 
                                    '', 
                                    [
                                        { text: t('common.cancel'), style: 'cancel' },
                                        { text: t('common.confirm'), onPress: handlePayment }
                                    ]
                                );
                            }}
                            extendedStyle={{ padding: 24, marginTop: 24 }}
                        />
                    </View>
                </View>
            </ScrollView>
        </SafeAreaView>
    );
};

export default PenaltyPaymentPageComponent;

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