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 NormalButton from '../global/normal_button';
import { useEffect, useState } from 'react';
import * as ImagePicker from 'expo-image-picker';
import * as SecureStore from 'expo-secure-store';
import * as FileSystem from 'expo-file-system';
import { authenticationService } from '../../service/authService';
import { FlashList } from '@shopify/flash-list';
import { walletService } from '../../service/walletService';
import { convertToHKTime } from '../../util/lib';
import { set } from 'date-fns';

interface TransactionRecordItem {
    date: string;
    description: string;
    amount: number;
}
const TransactionRow: React.FC<TransactionRecordItem> = ({ date, description, amount }) => (
    <View className="flex flex-row w-full my-4">
        <Text className="flex-[0.3]">{date}</Text>
        <Text className="flex-[0.3] text-center ">{description}</Text>
        <Text className="flex-[0.4] text-right">{amount}</Text>
        <View className="border-t  border-[#CCCCCC]"></View>
    </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();
                const formattedData: TransactionRecordItem[] = response
                    .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
                    .map((item: any) => {
                        let description;
                        if (item.type === 'wallet') {
                            description = item.good_name === 'withdrawl' ? '充電完成-退回餘額' : '充電';
                        } else {
                            description = '充值';
                        }
                        return {
                            date: convertToHKTime(item.createdAt).hkDate,
                            description: description,
                            amount: item.amount
                        };
                    });
                setTransactionRecord(formattedData.slice(0, 10));
            } catch (error) {
                console.log(error);
            }
        };
        fetchTransactionRecord();
    }, []);

    //fetch transaction record

    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 my-2">
                    <Text className="flex-[0.3] text-[#888888] ">日期</Text>
                    <Text className="flex-[0.3] text-center text-[#888888]">內容</Text>
                    <Text className="flex-[0.4] 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} />
                    )}
                    estimatedItemSize={10}
                />
            </ScrollView>
        </SafeAreaView>
    );
};

export default PaymentRecordPageComponent;
