import AppText from "@/components/ui/app-text";
import BackButtonTitle from "@/components/ui/BackButtonTitle";
import Button from "@/components/ui/Button";
import { useGetQuery } from "@/hooks/mutate/useGetQuery";
import { useColor } from "@/hooks/useColor";
import { useCurrency } from "@/hooks/useCurrency";
import { useAuthStore } from "@/providers/AuthStoreProviders";
import { useTranslations } from "@/providers/TranslationProviders";
import { Image } from "expo-image";
import { router } from "expo-router";
import moment from "moment";
import { ArrowUpRightIcon, ArticleIcon, ClockIcon, WalletIcon } from "phosphor-react-native";
import { useCallback, useEffect, useRef, useState } from "react";
import { ActivityIndicator, FlatList, Pressable, RefreshControl, Text, View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";

export default function Withdraw() {
  const { tran } = useTranslations();
  const { user } = useAuthStore((state) => state);
  const { primary } = useColor();
  const { currency } = useCurrency();
  const { translateNumber } = useTranslations();

  const [page, setPage] = useState(1);
  const [items, setItems] = useState<any[]>([]);
  const [hasMore, setHasMore] = useState(true);
  const isInitialMount = useRef(true);

  const {
    data: withdrawData,
    isFetching,
    refetch,
  } = useGetQuery({
    url: `/client/withdraws`,
    params: { page },
  });

  useEffect(() => {
    if (withdrawData?.data) {
      if (page === 1) {
        setItems(withdrawData.data);
      } else {
        setItems((prev) => {
          const existingIds = new Set(prev.map((i: any) => i.id));
          const newItems = withdrawData.data.filter((i: any) => !existingIds.has(i.id));
          return [...prev, ...newItems];
        });
      }
      setHasMore(withdrawData.current_page < withdrawData.last_page);
    }
  }, [withdrawData, page]);

  const onRefresh = useCallback(() => {
    setPage(1);
    refetch();
  }, [refetch]);

  const loadMore = () => {
    if (!isFetching && hasMore) {
      setPage((prev) => prev + 1);
    }
  };

  const getStatusColor = (status: string) => {
    switch (status.toLowerCase()) {
      case "confirmed":
      case "approved":
        return { bg: "#f0fdf4", text: "#16a34a" };
      case "pending":
        return { bg: "#fefce8", text: "#ca8a04" };
      case "rejected":
      case "failed":
        return { bg: "#fef2f2", text: "#dc2626" };
      default:
        return { bg: "#f1f5f9", text: "#64748b" };
    }
  };

  return (
    <SafeAreaView  className="bg-slate-50 h-full">
      <View className="px-5 bg-slate-50 pt-2">
        <BackButtonTitle title={tran("Withdrawal")} />
      </View>

      <FlatList
        data={items}
        keyExtractor={(item, idx) => `withdraw-${item.id ?? idx}-${idx}`}
        showsVerticalScrollIndicator={false}
        onEndReached={loadMore}
        onEndReachedThreshold={0.5}
        refreshControl={<RefreshControl refreshing={isFetching && page === 1} onRefresh={onRefresh} />}
        ListHeaderComponent={
          <View className="px-5 py-6">
            {/* Balance Card */}
            <View className="rounded-[32px] p-8 mb-6" style={{ backgroundColor: primary[5] }}>
              <View className="flex-row items-center gap-2.5 mb-2">
                <View className="size-10 rounded-xl justify-center items-center shadow-sm" style={{ backgroundColor: "white" }}>
                  <WalletIcon size={20} color={primary.base} weight="fill" />
                </View>
                <AppText className="text-slate-500 font-manrope-extrabold text-sm uppercase tracking-widest">{tran("Active Balance")}</AppText>
              </View>

              <AppText size="xxl" className="font-manrope-extrabold text-slate-900 pb-8 pt-4">
                {currency.symbol}
                {translateNumber(user?.balance || 0)}
              </AppText>

              <Button onPress={() => router.push("/(screens)/wallet/withdraw/create")} text={tran("Withdraw Funds")} />
            </View>

            <View className="flex-row justify-between items-center mb-6 px-1">
              <View>
                <AppText size="xl" className="font-manrope-extrabold text-slate-800">
                  {tran("Activity")}
                </AppText>
                <Text className="text-slate-400 font-manrope-semibold text-xs mt-0.5">{tran("Review your latest transactions")}</Text>
              </View>
              <View className="size-10 rounded-full justify-center items-center bg-white border border-slate-100">
                <ClockIcon size={20} color={primary.base} weight="duotone" />
              </View>
            </View>
          </View>
        }
        renderItem={({ item }) => {
          const statusColors = getStatusColor(item.status);
          return (
            <Pressable className="mx-5 mb-5 bg-white rounded-[32px] p-6 shadow-sm border border-slate-100/60">
              <View className="flex-row justify-between items-start mb-6">
                <View className="flex-row items-center gap-x-4">
                  <View className="size-14 rounded-2xl items-center justify-center border border-slate-100/50 shadow-sm" style={{ backgroundColor: primary[5] }}>
                    {item.method?.image ? (
                      <Image source={{ uri: item.method?.image }} className="size-full rounded-2xl" contentFit="cover" />
                    ) : (
                      <View className="size-full rounded-2xl items-center justify-center">
                        <ArrowUpRightIcon size={24} color={primary.base} weight="bold" />
                      </View>
                    )}
                  </View>
                  <View>
                    <Text className="text-lg font-manrope-bold text-slate-800 tracking-tight">{item.method?.name}</Text>
                    <Text className="text-[11px] text-slate-400 font-manrope-bold uppercase tracking-widest mt-0.5" numberOfLines={1}>
                      {item.track || item.transaction_id}
                    </Text>
                  </View>
                </View>

                <View className="px-3.5 py-1.5 rounded-full shadow-sm" style={{ backgroundColor: statusColors.bg }}>
                  <Text className="text-[10px] font-manrope-extrabold uppercase tracking-widest" style={{ color: statusColors.text }}>
                    {tran(item.status)}
                  </Text>
                </View>
              </View>

              <View className="flex-row justify-between items-center pt-5 border-t border-slate-50">
                <View className="flex-row items-center gap-x-2">
                  <View className="size-8 rounded-full items-center justify-center bg-slate-50">
                    <ArticleIcon size={14} color="#94a3b8" weight="bold" />
                  </View>
                  <View>
                    <Text className="text-slate-400 text-[10px] font-manrope-bold uppercase tracking-tighter">{tran("Created at")}</Text>
                    <Text className="text-slate-700 text-[13px] font-manrope-bold">{moment(item.created_at).format("DD MMM, YYYY")}</Text>
                  </View>
                </View>

                <View className="items-end bg-slate-50/80 px-4 py-2 rounded-2xl">
                  <Text className="text-slate-400 text-[10px] font-manrope-bold uppercase tracking-tighter mb-0.5">{tran("Payout")}</Text>
                  <AppText className="text-slate-900 font-manrope-extrabold text-lg">
                    {currency.symbol}
                    {translateNumber(item.amount)}
                  </AppText>
                </View>
              </View>
            </Pressable>
          );
        }}
        ListEmptyComponent={
          !isFetching ? (
            <View className="items-center justify-center py-20 opacity-40">
              <ClockIcon size={48} color="#94a3b8" />
              <AppText className="mt-4 font-manrope-bold text-slate-400">{tran("No withdrawals found")}</AppText>
            </View>
          ) : null
        }
        ListFooterComponent={isFetching && page > 1 ? <ActivityIndicator style={{ margin: 16 }} color={primary.base} /> : null}
      />
    </SafeAreaView>
  );
}
