import React, { useState, useEffect, useCallback } from "react";
import { View, FlatList, TextInput, RefreshControl, ActivityIndicator, Text } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useGetQuery } from "@/hooks/mutate/useGetQuery";
import { useColor } from "@/hooks/useColor";
import { useCurrency } from "@/hooks/useCurrency";
import { useTranslations } from "@/providers/TranslationProviders";
import { ArrowDownLeftIcon, ArrowUpRightIcon, MagnifyingGlassIcon } from "phosphor-react-native";
import BackButtonTitle from "@/components/ui/BackButtonTitle";
import AppText from "@/components/ui/app-text";
import NoDataFound from "@/components/ui/no-data-found";

interface Transaction {
  id: number;
  transaction_id: string;
  amount: number;
  type: string;
  is_debit: boolean;
  created_at: string;
  note: string;
}

const formatTransactionType = (type: string): string => {
  const typeMap: Record<string, string> = {
    share_purchase: "Share Purchase",
    share_sale: "Share Sale",
    deposit: "Deposit",
    withdrawal: "Withdrawal",
    roi_credit: "ROI Credited",
    referral_bonus: "Referral Bonus",
    dividend: "Dividend",
  };
  return typeMap[type] || type.replace(/_/g, " ").replace(/\b\w/g, (c: string) => c.toUpperCase());
};

const TransactionCard = ({ item }: { item: Transaction }) => {
  const { success, danger } = useColor();
  const { currency } = useCurrency();
  const { tran, translateNumber } = useTranslations();

  return (
    <View className="flex-row justify-between items-center bg-white rounded-[28px] p-4 mb-4 border border-slate-100 shadow-sm shadow-slate-50">
      <View className="flex-row justify-start items-center gap-4 flex-1">
        <View className={`size-12 rounded-2xl justify-center items-center ${!item.is_debit ? 'bg-emerald-50' : 'bg-rose-50' }`}>
          {!item.is_debit ? (
            <ArrowDownLeftIcon color={success.base} size={22} weight="bold" />
          ) : (
            <ArrowUpRightIcon color={danger.base} size={22} weight="bold" />
          )}
        </View>
        <View className="flex-1">
          <AppText className="text-sm font-manrope-extrabold text-slate-800" numberOfLines={1}>
            {tran(formatTransactionType(item.type))}
          </AppText>
          <View className="flex-row items-center gap-1.5 pt-0.5">
            <AppText className="text-[10px] text-slate-400 font-manrope-bold uppercase tracking-tight">
              #{item.transaction_id.slice(0, 10)}
            </AppText>
             <View className="w-1 h-1 rounded-full bg-slate-200" />
            <AppText className="text-[10px] text-slate-400 font-manrope-semibold">
              {new Date(item.created_at).toLocaleDateString()}
            </AppText>
          </View>
        </View>
      </View>
      <View className="pl-3 items-end">
        <Text 
          className="text-base font-manrope-extrabold"
          style={{ color: !item.is_debit ? success.base : danger.base }}
        >
          {!item.is_debit ? "+" : "-"} {currency.symbol}{translateNumber(Math.abs(item.amount).toFixed(2))}
        </Text>
      </View>
    </View>
  );
};

export default function TransactionsScreen() {
  const insets = useSafeAreaInsets();
  const { primary } = useColor();
  const { tran } = useTranslations();
  
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(1);
  const [items, setItems] = useState<Transaction[]>([]);

  const { data, isLoading, isFetching, refetch } = useGetQuery({
    url: "/client/transactions",
    params: {
      page,
      search: search || undefined,
    },
  });

  useEffect(() => {
    if (data?.data) {
      if (page === 1) {
        setItems(data.data);
      } else {
        setItems((prev) => [...prev, ...data.data]);
      }
    }
  }, [data, page]);

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

  const loadMore = () => {
    if (data?.current_page < data?.last_page && !isFetching) {
      setPage((prev) => prev + 1);
    }
  };

  return (
    <View className="flex-1 bg-white" style={{ paddingTop: insets.top }}>
      {/* Scrollable Content inside a View to manage header/search separately if needed */}
      <View className="px-4 pt-2 pb-4">
        <BackButtonTitle title={tran("Transactions")} />
      </View>

      <View className="px-4 pb-6">
        <View className="flex-row items-center bg-slate-50 border border-slate-100 rounded-[22px] px-4 py-1.5 shadow-sm shadow-slate-50">
          <MagnifyingGlassIcon size={20} color="#64748b" weight="bold" />
          <TextInput
            className="flex-1 h-12 ml-2 font-manrope-semibold text-slate-800"
            placeholder={tran("Search by ID...")}
            placeholderTextColor="#94a3b8"
            value={search}
            onChangeText={(text) => {
              setSearch(text);
              setPage(1);
            }}
          />
        </View>
      </View>

      <FlatList
        data={items}
        keyExtractor={(item, index) => `${item.id}-${index}`}
        renderItem={({ item }) => <TransactionCard item={item} />}
        contentContainerStyle={{ 
          paddingHorizontal: 16, 
          paddingBottom: insets.bottom + 40,
          flexGrow: 1 
        }}
        showsVerticalScrollIndicator={false}
        refreshControl={
          <RefreshControl refreshing={Boolean(isFetching && page === 1)} onRefresh={onRefresh} tintColor={primary.base} />
        }
        onEndReached={loadMore}
        onEndReachedThreshold={0.5}
        ListEmptyComponent={
          !isLoading && !isFetching && data && items.length === 0 ? (
            <View className="flex-1 justify-center py-20">
              <NoDataFound 
                title={tran("No Transactions Found")} 
                description={tran("Your activity will appear here once you start.")}
                bordered={false}
              />
            </View>
          ) : isLoading && page === 1 ? (
            <View className="gap-y-4">
                 {[1,2,3,4,5,6,7].map(i => (
                    <View key={i} className="h-24 bg-slate-50 rounded-[28px] animate-pulse border border-slate-100" />
                 ))}
            </View>
          ) : null
        }
        ListFooterComponent={
          isFetching && page > 1 ? (
            <View className="py-6 items-center">
              <ActivityIndicator color={primary.base} />
            </View>
          ) : null
        }
      />
    </View>
  );
}
