import { useGetQuery } from "@/hooks/mutate/useGetQuery";
import { useColor } from "@/hooks/useColor";
import { useCurrency } from "@/hooks/useCurrency";
import { useTranslations } from "@/providers/TranslationProviders";
import { ArrowDownLeftIcon, ArrowUpRightIcon, ClockIcon } from "phosphor-react-native";
import { Pressable, Text, View } from "react-native";
import { router } from "expo-router";
import AppText from "../ui/app-text";

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

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) => c.toUpperCase());
};

const formatRelativeTime = (dateString: string): string => {
  const date = new Date(dateString);
  const now = new Date();
  const diffMs = now.getTime() - date.getTime();
  const diffMins = Math.floor(diffMs / 60000);
  const diffHours = Math.floor(diffMs / 3600000);
  const diffDays = Math.floor(diffMs / 86400000);

  if (diffMins < 1) return "Just now";
  if (diffMins < 60) return `${diffMins} min ago`;
  if (diffHours < 24) return `${diffHours} hour${diffHours > 1 ? "s" : ""} ago`;
  if (diffDays < 7) return `${diffDays} day${diffDays > 1 ? "s" : ""} ago`;
  return date.toLocaleDateString();
};

export default function RecentActivity() {
  const { primary, danger, success } = useColor();
  const { currency } = useCurrency();
  const { tran, translateNumber } = useTranslations();
  const { data } = useGetQuery({
    url: "/client/summary",
  });

  if (!data?.recent_transactions || data?.recent_transactions?.length === 0) return null;

  return (
    <View className="pt-8">
      <View className="flex-row justify-between items-center pb-6 px-1">
        <View className="flex-row items-center gap-2">
            <View className="w-8 h-8 rounded-lg bg-slate-100 items-center justify-center">
                <ClockIcon size={18} color="#64748b" weight="bold" />
            </View>
            <AppText className="text-xl font-manrope-extrabold text-slate-900">{tran("Recent Activity")}</AppText>
        </View>
        <Pressable onPress={() => router.push("/wallet/transactions" as any)}>
            <AppText
            className="font-manrope-bold text-sm"
            style={{
                color: primary.base,
            }}
            >
            {tran("See All")}
            </AppText>
        </Pressable>
      </View>

      <View className="gap-y-4">
        {data?.recent_transactions.map((item: Transaction) => (
          <View
            key={item.id}
            className="flex-row justify-between items-center bg-white rounded-3xl p-3 border border-slate-100 shadow-sm shadow-slate-50"
          >
            <View className="flex-row justify-start items-center gap-3.5">
              <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={20} weight="bold" />
                  ) : (
                      <ArrowUpRightIcon color={danger.base} size={20} weight="bold" />
                  )}
              </View>
              <View>
                <AppText className="text-base font-manrope-extrabold text-slate-800">
                    {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-tighter">
                        #{item.transaction_id.slice(0, 8)}
                    </AppText>
                    <View className="w-1 h-1 rounded-full bg-slate-200" />
                    <AppText className="text-[10px] text-slate-400 font-manrope-semibold">
                        {formatRelativeTime(item.created_at)}
                    </AppText>
                </View>
              </View>
            </View>
            <View className="justify-end items-end pr-1">
              <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>
        ))}
      </View>
    </View>
  );
}
