import {
    View,
    Text,
    ScrollView,
    Pressable,
    Image,
    Dimensions,
    ImageBackground,
    BackHandler,
    Alert
} from 'react-native';
import React, { useCallback, useEffect, useState } from 'react';
import { SafeAreaView } from 'react-native-safe-area-context';
import { router, useFocusEffect, useNavigation } from 'expo-router';
import { CrossLogoSvg, PreviousPageBlackSvg, RightArrowIconSvg } from '../../../../component/global/SVG';
import { useChargingStore } from '../../../../providers/scan_qr_payload_store';
import { walletService } from '../../../../service/walletService';
import { chargeStationService } from '../../../../service/chargeStationService';

const optionPage = () => {
    const {
        total_power,
        setTotalPower,
        promotion_code,
        setPromotionCode,
        sum_of_coupon,
        setSumOfCoupon,
        setCouponDetail,
        current_price_store,
        setCurrentPriceStore,
        setProcessedCouponStore
    } = useChargingStore();
    const buttonText = [
        {
            power: '20度電',
            minute: '25分鐘',
            total_power: 20
        },
        {
            power: '25度電',
            minute: '30分鐘',
            total_power: 25
        },
        {
            power: '30度電',
            minute: '40分鐘',
            total_power: 30
        },
        {
            power: '40度電',
            minute: '45分鐘',
            total_power: 40
        },
        {
            power: '充滿停機',
            minute: '最多80度電',
            total_power: 80
        }
    ];
    const screenWidth = Dimensions.get('window').width;
    const [useableCoupon, setUseableCoupon] = useState([]);
    const navigation = useNavigation();

    //forbid user leftswipping
    useEffect(() => {
        navigation.setOptions({
            gestureEnabled: false
        });
    }, [navigation]);

    // 优惠券注释

    useEffect(() => {
        const fetchData = async () => {
            try {
                const info = await walletService.getCustomerInfo();
                const coupon = await walletService.getCouponForSpecificUser(info.id);
                //filter by expire date is not past today.and is_consumed is fa.se.
                const useableConpon = coupon.filter((couponObj: any) => {
                    const today = new Date();
                    if (couponObj.expire_date === null) {
                        return couponObj.is_consumed === false;
                    }
                    const expireDate = new Date(couponObj.expire_date);
                    return expireDate > today && couponObj.is_consumed === false;
                });
                setUseableCoupon(useableConpon);
            } catch (error) {}
        };
        fetchData();
    }, []);
    const cleanupData = () => {
        setTotalPower(null);
        setSumOfCoupon(0);
        setPromotionCode([]);
        setCouponDetail([]);
        setProcessedCouponStore([]);
    };

    // Add this effect to handle Android back button
    useFocusEffect(
        useCallback(() => {
            const onBackPress = () => {
                cleanupData();
                if (router.canGoBack()) {
                    router.back();
                } else {
                    router.replace('/scanQrPage');
                }
                return true;
            };

            const subscription = BackHandler.addEventListener('hardwareBackPress', onBackPress);

            return () => subscription.remove();
        }, [])
    );

    const displayedText =
        promotion_code.length > 0 ? `$ ${sum_of_coupon}劵` : useableCoupon.length > 0 ? '有可用劵' : '無可用劵';

    return (
        <SafeAreaView className="flex-1 bg-white" edges={['top', 'right', 'left']}>
            <ScrollView className="flex-1 mx-[5%]" showsVerticalScrollIndicator={false}>
                <View style={{ marginTop: 25 }}>
                    <Pressable
                        onPress={() => {
                            if (router.canGoBack()) {
                                cleanupData();
                                router.back();
                            } else {
                                cleanupData();
                                router.replace('/scanQrPage');
                            }
                        }}
                    >
                        <PreviousPageBlackSvg />
                    </Pressable>
                </View>
                <View className="flex-1 flex-col justify-center items-center">
                    {/* top word and logo */}
                    <View className="flex-col justify-center items-center gap-2">
                        {/* <Text className="text-2xl"> */}
                        <Text className="text-2xl font-[600]">選擇充電度數</Text>
                        <Image
                            source={require('../../../../assets/battery.png')}
                            style={{ width: screenWidth * 0.3, height: undefined, aspectRatio: 1 }}
                            className="mb-2 md:mb-4 lg:mb-4 xl:mb-6  "
                        />
                    </View>
                    {/* middle button */}
                    <View className="flex-1 w-full mt-6">
                      <View className="flex-row flex-wrap justify-center items-center gap-4 ">
                          {/* not showing full power because it needs to be full width */}
                          {buttonText
                              .filter((item) => item.power != '充滿停機')
                              .map((buttonTextObj: any, index) => (
                                  <Pressable
                                      key={index}
                                      className={`${total_power === buttonTextObj.total_power ? 'bg-[#02677D]' : ''}
                                      w-[45%] border border-[#02677D] p-1 md:p-2 lg:p-3 xl:p-4 py-4 lg:py-6 rounded-xl`}
                                      onPress={() => {
                                          setTotalPower(buttonTextObj.total_power);
                                      }}
                                  >
                                      <Text
                                          className={`${
                                              total_power === buttonTextObj.total_power
                                                  ? 'text-white'
                                                  : 'text-[#02677D]'
                                          } text-base lg:text-lg xl:text-xl text-center`}
                                      >
                                          {buttonTextObj.power}({buttonTextObj.minute})
                                      </Text>
                                  </Pressable>
                              ))}
                          {/* this is 充滿停機only */}
                          {buttonText
                              .filter((item) => item.power === '充滿停機')
                              .map((item, index) => (
                                  <Pressable
                                      key={index}
                                      onPress={() => {
                                          setTotalPower(item.total_power);
                                      }}
                                      className={`${
                                          total_power === item.total_power ? 'bg-[#02677D]' : ''
                                      } w-[94%] border border-[#02677D] p-1 md:p-2 lg:p-3 xl:p-4 py-4 lg:py-6 rounded-xl`}
                                  >
                                      <Text
                                          className={`${
                                              total_power === item.total_power ? 'text-white' : 'text-[#02677D]'
                                          } text-base lg:text-lg xl:text-xl text-center`}
                                      >
                                          {item.power}({item.minute})
                                      </Text>
                                  </Pressable>
                              ))}
                        </View>
                        {/* coupon row */}
                        <Pressable
                            onPress={() => {
                                if (!total_power) {
                                    Alert.alert(
                                        '選擇充電方案',
                                        '請先選擇充電方案再選擇優惠券',
                                        [{ text: '確定', style: 'default' }],
                                        {
                                            cancelable: true
                                        }
                                    );
                                } else {
                                    Alert.alert('提醒您', '使用優惠券的交易每度電以正價$3.5元計算!', [
                                        { text: '我知道了', onPress: () => router.push('/selectCoupon') }
                                    ]);
                                }
                            }}
                            style={{ flex: 1, borderRadius: 10, overflow: 'hidden', marginTop: 10 }}
                        >
                            <ImageBackground
                                source={require('../../../../assets/coupon.png')}
                                style={{
                                    width: '100%',
                                    height: 72,
                                    borderRadius: 24,
                                    justifyContent: 'center',
                                    alignItems: 'flex-end'
                                }}
                                resizeMode="contain"
                            >
                                <Text className="text-white text-center text-base lg:text-lg xl:text-xl pr-6 md:pr-8 lg:pr-10 xl:pr-12">
                                    {displayedText}
                                </Text>
                            </ImageBackground>
                        </Pressable>
                    </View>

                    {/* confirm and cancel  */}
                    <View className="flex-row flex-wrap justify-center items-center gap-4 my-8 lg:my-6">
                        <Pressable
                            onPress={() => {
                                cleanupData();
                                if (router.canGoBack()) {
                                    router.back();
                                } else {
                                    router.replace('/scanQrPage');
                                }
                            }}
                            className="w-[45%] border border-[#02677D] p-1 md:p-2 lg:p-3 xl:p-4 py-4 lg:py-6 rounded-xl "
                        >
                            <Text className="text-[#02677D] text-base lg:text-lg xl:text-xl text-center">取消</Text>
                        </Pressable>
                        <Pressable
                            onPress={() => {
                                if (!total_power) {
                                    Alert.alert(
                                        '選擇充電方案',
                                        '請先選擇充電方案再確認',
                                        [{ text: '確定', style: 'default' }],
                                        {
                                            cancelable: true
                                        }
                                    );
                                } else {
                                    router.push('/totalPayment');
                                }
                            }}
                            className="w-[45%] border border-[#02677D] p-1 md:p-2 lg:p-3 xl:p-4 py-4 lg:py-6 rounded-xl "
                        >
                            <Text className="text-[#02677D] text-base lg:text-lg xl:text-xl text-center">確認</Text>
                        </Pressable>
                    </View>
                </View>
            </ScrollView>
        </SafeAreaView>
    );
};

export default optionPage;
