import {
    View,
    Text,
    Pressable,
    Dimensions,
    ImageSourcePropType,
    useWindowDimensions,
    ScrollView,
    ActivityIndicator,
    StyleSheet
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { router } from 'expo-router';
import { CrossLogoSvg } from '../global/SVG';
import { useEffect, useState } from 'react';
import { walletService } from '../../service/walletService';
import { SceneMap, TabBar, TabView } from 'react-native-tab-view';
import React from 'react';

import { formatCouponDate } from '../../util/lib';
import useCouponStore from '../../providers/coupon_store';

export const SelectIndividualCouponComponent = ({
    title,
    price,
    detail,
    date,
    redeemCode,
    disabled = false
}: {
    title: string;
    price: string;
    detail: string;
    date: string;
    redeemCode: string;
    disabled: boolean;
}) => {
    const setSelectedCouponName = useCouponStore((state) => state.setSelectedCouponName);
    const setSelectedCouponRedeemCode = useCouponStore((state) => state.setSelectedCouponRedeemCode);
    const setSelectedCouponPrice = useCouponStore((state) => state.setSelectedCouponPrice);

    return (
        <Pressable
            disabled={disabled}
            onPress={() => {
                setSelectedCouponRedeemCode(redeemCode);
                setSelectedCouponName(title);
                setSelectedCouponPrice(price);
                router.push({
                    pathname: '/paymentSummaryPage'
                });
            }}
        >
            <View className="bg-[#e7f2f8] h-[124px]  rounded-xl flex-row mb-3">
                <View className="bg-white mx-3 my-3 w-[28%] rounded-xl">
                    <View className="flex-row justify-center items-center pr-4 pt-4 ">
                        <Text className="color-[#02677d] text-2xl pl-2 pr-1">$</Text>
                        <Text className="color-[#02677d] text-3xl font-bold" adjustsFontSizeToFit={true}>
                            {price}
                        </Text>
                    </View>
                    <View className="items-center justify-center">
                        <Text className="text-base mt-1">{title}</Text>
                    </View>
                </View>

                {/* //dash line */}
                <View style={{ overflow: 'hidden' }}>
                    <View
                        style={{
                            borderStyle: 'dashed',
                            borderWidth: 1,
                            borderColor: '#CCCCCC',
                            margin: -1,
                            width: 0,
                            marginRight: 0,
                            height: '100%'
                        }}
                    >
                        <View style={{ height: 60 }}></View>
                    </View>
                </View>

                <View className="flex-col flex-1  m-[5%] justify-center ">
                    <Text className="text-lg">{title}</Text>
                    <Text className="color-[#888888] text-sm">{detail}</Text>
                    <View className="flex-row items-center ">
                        <Text className="text-base">有效期 </Text>
                        <Text className="text-base font-bold text-[#02677d]">{date}</Text>
                    </View>
                </View>
            </View>
        </Pressable>
    );
};

export interface TabItem {
    imgURL: ImageSourcePropType;
    date: string;
    time: string;
    chargeStationName: string;
    chargeStationAddress: string;
    distance: string;
}

interface TabViewComponentProps {
    titles: string[];
}

export const SelectCouponTabViewComponent: React.FC<TabViewComponentProps> = ({ titles }) => {
    const layout = useWindowDimensions();
    const [loading, setLoading] = useState(false);
    const [coupons, setCoupons] = useState([]);
    const [userID, setUserID] = useState('');

    useEffect(() => {
        const fetchData = async () => {
            try {
                setLoading(true);
                const info = await walletService.getCustomerInfo();
                const coupon = await walletService.getCouponForSpecificUser(userID);
                setUserID(info.id);
                setCoupons(coupon);
            } catch (error) {
                console.log(error);
            } finally {
                setLoading(false);
            }
        };
        fetchData();
    }, []);

    //tab 1
    const FirstRoute = () => (
        <ScrollView style={{ flex: 1, backgroundColor: 'white', marginTop: 14 }}>
            <View className="flex-1 flex-col">
                {loading ? (
                    <View className="items-center justify-center">
                        <ActivityIndicator />
                    </View>
                ) : (
                    <View>
                        {coupons.filter(
                            (coupon) => coupon.is_consumed === false && new Date(coupon.expire_date) > new Date()
                        ).length === 0 ? (
                            <Text className="pl-4">暫時戶口沒有優惠券。</Text>
                        ) : (
                            coupons
                                .filter(
                                    (coupon) =>
                                        coupon.is_consumed === false && new Date(coupon.expire_date) > new Date()
                                )
                                .slice(0, 2)
                                .map((coupon, index) => (
                                    <SelectIndividualCouponComponent
                                        key={`${coupon.id}-${index}`}
                                        title={coupon.coupon.name}
                                        price={coupon.coupon.amount}
                                        detail={coupon.coupon.description}
                                        date={formatCouponDate(coupon.expire_date)}
                                        redeemCode={coupon.id}
                                        disabled={false}
                                    />
                                ))
                        )}
                    </View>
                )}
            </View>
        </ScrollView>
    );

    //tab 2
    const SecondRoute = () => (
        <ScrollView style={{ flex: 1, backgroundColor: 'white', marginTop: 14 }}>
            <View className="flex-1 flex-col">
                {coupons
                    .filter((coupon) => coupon.is_consumed === true || new Date(coupon.expire_date) < new Date())
                    .slice(0, 2)
                    .map((coupon, index) => (
                        <SelectIndividualCouponComponent
                            key={index}
                            title={coupon.name}
                            price={coupon.amount}
                            detail={coupon.description}
                            date={formatCouponDate(coupon.expire_date)}
                            redeemCode={coupon.id}
                            disabled={true}
                        />
                    ))}
            </View>
        </ScrollView>
    );

    const renderScene = SceneMap({
        firstRoute: FirstRoute,
        secondRoute: SecondRoute
    });
    const [routes] = React.useState([
        { key: 'firstRoute', title: titles[0] },
        { key: 'secondRoute', title: titles[1] }
    ]);
    const [index, setIndex] = React.useState(0);

    const renderTabBar = (props: any) => (
        <TabBar
            {...props}
            renderLabel={({ route, focused }) => (
                <Text
                    style={{
                        color: focused ? '#025c72' : '#888888',
                        fontWeight: focused ? '900' : 'thin',
                        fontSize: 20
                    }}
                >
                    {route.title}
                </Text>
            )}
            indicatorStyle={{
                backgroundColor: '#025c72'
            }}
            style={{
                backgroundColor: 'white',
                borderColor: '#DBE4E8',
                elevation: 0,
                marginHorizontal: 15,
                borderBottomWidth: 0.5
            }}
        />
    );
    return (
        <TabView
            navigationState={{ index, routes }}
            renderScene={renderScene}
            onIndexChange={setIndex}
            initialLayout={{ width: layout.width }}
            renderTabBar={renderTabBar}
        />
    );
};

const styles = StyleSheet.create({
    container: { flexDirection: 'row' },
    image: { width: 100, height: 100, margin: 15, borderRadius: 10 },
    textContainer: { flexDirection: 'column', gap: 8, marginTop: 20 }
});

const SelectCouponPageComponent = () => {
    const screenHeight = Dimensions.get('window').height;
    return (
        <SafeAreaView className="flex-1 bg-white" edges={['top', 'right', 'left']}>
            <View style={{ minHeight: screenHeight, flex: 1 }} className="mx-[5%]">
                <View style={{ marginTop: 25 }}>
                    <Pressable
                        onPress={() => {
                            if (router.canGoBack()) {
                                router.back();
                            } else {
                                router.replace('/accountMainPage');
                            }
                        }}
                    >
                        <CrossLogoSvg />
                    </Pressable>
                    <Text style={{ fontSize: 45, marginVertical: 25 }}>選擇優惠券</Text>
                </View>
                <View className="flex-1 ">
                    <SelectCouponTabViewComponent titles={['可用優惠券', '已使用/失效']} />
                </View>
            </View>
        </SafeAreaView>
    );
};

export default SelectCouponPageComponent;
