import { View, Text, Pressable, Image, ScrollView, Alert, ImageBackground, ActivityIndicator } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { router, useLocalSearchParams } from 'expo-router';
import { PreviousPageBlackSvg } from '../global/SVG';
import { useEffect, useState } from 'react';
import { authenticationService } from '../../service/authService';
import { FlashList } from '@shopify/flash-list';
import { walletService } from '../../service/walletService';
import { convertToHKTime } from '../../util/lib';

interface TransactionRecordItem {
    date: string;
    description: string;
    amount: number;
    actual_total_power: string | number;
    current_price?: number;
}
const TransactionRow: React.FC<TransactionRecordItem> = ({
    date,
    description,
    amount,
    actual_total_power,
    current_price
}) => (
    <View className="flex flex-row w-full py-4 border-b border-[#CCCCCC]">
        <Text className="flex-[0.2] text-sm">{date}</Text>
        <Text className="flex-[0.2] text-center text-sm">{description}</Text>
        <Text className="flex-[0.2] text-sm text-right ">
            {actual_total_power !== '-' ? Number(actual_total_power).toFixed(1) : actual_total_power}
        </Text>
        <Text className="flex-[0.2] text-sm text-right">{current_price ? `${current_price}` : '-'}</Text>
        <Text className="flex-[0.2] text-sm text-right">${amount}</Text>
    </View>
);
const PaymentRecordPageComponent = () => {
    const params = useLocalSearchParams();
    const walletBalance = params.walletBalance;
    const [transactionRecord, setTransactionRecord] = useState<TransactionRecordItem[]>([]);
    const [loading, setLoading] = useState(false);
    const [loading1, setLoading1] = useState(false);

    // useEffect(() => {
    //     const fetchTransactionRecord = async () => {
    //         try {
    //             const response = await walletService.getTransactionRecord();
    //             console.log('response', response);
    //             const formattedData: TransactionRecordItem[] = response
    //                 .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
    //                 .map((item: any) => {
    //                     let description;
    //                     if (item.type === 'wallet') {
    //                         switch (item.goods_name) {
    //                             case 'withdrawl':
    //                                 description = '充電完成-退回餘額';
    //                                 break;
    //                             case 'Penalty':
    //                                 description = '繳付罰款';
    //                                 break;
    //                             case 'Book a connector':
    //                                 description = '預約充電費用';
    //                                 break;
    //                             case 'Walk In':
    //                                 description = '充電費用';
    //                                 break;
    //                             default:
    //                                 description = '充電';
    //                         }
    //                     } else {
    //                         description = '錢包增值';
    //                     }
    //                     return {
    //                         date: convertToHKTime(item.createdAt).hkDate,
    //                         description: description,
    //                         amount: item.amount,
    //                         actual_total_power:
    //                             item.actual_total_power !== undefined &&
    //                             item.actual_total_power !== null &&
    //                             item.actual_total_power !== '' &&
    //                             !isNaN(Number(item.actual_total_power))
    //                                 ? item.actual_total_power
    //                                 : '-'
    //                     };
    //                 });
    //             setTransactionRecord(formattedData.slice(0, 10));
    //             console.log('transactionRecord', transactionRecord);
    //         } catch (error) {
    //             console.log(error);
    //         }
    //     };
    //     fetchTransactionRecord();
    // }, []);

    //fetch transaction record

    useEffect(() => {
        const fetchTransactionRecord = async () => {
            try {
                const response = await walletService.getTransactionRecord();
                const formattedData: TransactionRecordItem[] = response
                    .sort((a: any, b: any) => new Date(b.createdAt) - new Date(a.createdAt))
                    .filter(
                        (item: any) =>
                            item.type !== 'wallet' ||
                            item.goods_name === 'Penalty' ||
                            item.goods_name === 'manual_refund' ||
                            item.goods_name === 'manual_deduction' ||
                            (item.goods_name === 'Walk In' && Number(item.actual_total_power) >= 1)
                    )
                    .map((item: any) => {
                        let description;
                        if (item.type === 'wallet') {
                            switch (item.goods_name) {
                                case 'withdrawl':
                                    description = '充電完成-退回餘額';
                                    break;
                                case 'Penalty':
                                    description = '繳付罰款';
                                    break;
                                case 'Book a connector':
                                    description = '預約充電概要';
                                    break;
                                case 'Walk In':
                                    description = '充電概要';
                                    break;
                                case 'manual_refund':
                                    description = '系統退款';
                                    break;
                                case 'manual_deduction':
                                    description = '系統扣款';
                                    break;
                                default:
                                    description = '充電';
                            }
                        } else if (item.type === 'qfpay') {
                            description = '錢包增值';
                        }

                        return {
                            date: convertToHKTime(item.createdAt).hkDate,
                            description: description,
                            amount:
                                item.type === 'qfpay' ||
                                item.goods_name === 'Penalty' ||
                                item.goods_name === 'manual_refund' ||
                                item.goods_name === 'manual_deduction'
                                    ? item.amount
                                    : item.current_price && item.actual_total_power
                                      ? (item.current_price * item.actual_total_power).toFixed(1)
                                      : '-',
                            actual_total_power:
                                item.goods_name === 'manual_refund' || item.goods_name === 'manual_deduction'
                                    ? '-'
                                    : item.actual_total_power !== undefined &&
                                        item.actual_total_power !== null &&
                                        item.actual_total_power !== '' &&
                                        !isNaN(Number(item.actual_total_power))
                                      ? item.actual_total_power
                                      : '-',
                            current_price:
                                item.type === 'qfpay' ||
                                item.goods_name === 'Penalty' ||
                                item.goods_name === 'manual_refund' ||
                                item.goods_name === 'manual_deduction'
                                    ? '-'
                                    : item.current_price
                        };
                    });
                setTransactionRecord(formattedData.slice(0, 10));
            } catch (error) {}
        };
        fetchTransactionRecord();
    }, []);

    return (
        <SafeAreaView className="flex-1 bg-white" edges={['top', 'right', 'left']}>
            <ScrollView style={{ flex: 1 }} className="mx-[5%]" showsVerticalScrollIndicator={false}>
                <View style={{ marginTop: 25 }}>
                    <Pressable
                        onPress={() => {
                            if (router.canGoBack()) {
                                router.back();
                            } else {
                                router.replace('/accountMainPage');
                            }
                        }}
                    >
                        <PreviousPageBlackSvg />
                    </Pressable>
                    <Text style={{ fontSize: 45, marginVertical: 25 }}>订单記錄</Text>
                </View>
                <View className="">
                    <ImageBackground
                        className="flex-col-reverse shadow-lg"
                        style={{ height: 200 }}
                        source={require('../../assets/walletCard1.png')}
                        resizeMode="contain"
                    >
                        <View className="mx-[5%] pb-6">
                            <Text className="text-white text-xl">餘額 (HKD)</Text>
                            <View className="flex-row  items-center justify-between ">
                                <Text style={{ fontSize: 52 }} className=" text-white font-bold">
                                    {loading ? (
                                        <View className="items-center justify-center">
                                            <ActivityIndicator />
                                        </View>
                                    ) : (
                                        <>
                                            <Text>$</Text> {walletBalance}
                                        </>
                                    )}
                                </Text>
                            </View>
                        </View>
                    </ImageBackground>
                </View>
                <View className="flex flex-row w-full py-2 border-b border-[#CCCCCC]">
                    <Text className="flex-[0.2] text-sm text-[#888888]">日期</Text>
                    <Text className="flex-[0.2] text-sm text-center text-[#888888]">內容</Text>
                    <Text className="flex-[0.2] text-sm text-right text-[#888888]">實際充電量</Text>
                    <Text className="flex-[0.2] text-sm text-right text-[#888888]">電價</Text>
                    <Text className="flex-[0.2] text-sm text-right text-[#888888]">金額</Text>
                </View>
                <View className="border-t  border-[#CCCCCC]" />

                <FlashList
                    data={transactionRecord}
                    renderItem={({ item }) => (
                        <TransactionRow
                            date={item.date}
                            description={item.description}
                            amount={item.amount}
                            actual_total_power={item.actual_total_power}
                            current_price={item.current_price}
                        />
                    )}
                />
            </ScrollView>
        </SafeAreaView>
    );
};

export default PaymentRecordPageComponent;
