import BackButtonTitle from "@/components/ui/BackButtonTitle";
import { useGetQuery } from "@/hooks/mutate/useGetQuery";
import { useColor } from "@/hooks/useColor";
import { useCurrency } from "@/hooks/useCurrency";
import { useTranslations } from "@/providers/TranslationProviders";
import { formatDate } from "@/utils/helper";
import { CalendarIcon, ClockCounterClockwiseIcon, ClockIcon, WalletIcon, WarningCircleIcon } from "phosphor-react-native";
import { ActivityIndicator, RefreshControl, ScrollView, Text, View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";

export default function ROIReceivedScreen() {
  const { primary, secondary, danger, success } = useColor();
  const { tran, translateNumber } = useTranslations();
  const { currency } = useCurrency();
  const {
    data: summary,
    isLoading: summaryLoading,
    refetch: refetchSummary,
  } = useGetQuery({
    url: "/client/payouts/paid-summary",
  });

  const {
    data: payouts,
    isLoading: payoutsLoading,
    refetch: refetchPayouts,
  } = useGetQuery({
    url: "/client/payouts/paid",
  });

  const onRefresh = () => {
    refetchSummary();
    refetchPayouts();
  };

  const stats = [
    {
      icon: WalletIcon,
      title: "Total Paid",
      value: summary?.total_paid || 0,
      color: primary.base,
      bg: primary[10],
    },
    {
      icon: CalendarIcon,
      title: "This Month",
      value: summary?.this_month_paid || 0,
      color: secondary.base,
      bg: secondary[10],
    },
    {
      icon: ClockCounterClockwiseIcon,
      title: "Last Month",
      value: summary?.last_month_paid || 0,
      color: "#6366f1",
      bg: "#eef2ff",
    },
    {
      icon: WarningCircleIcon,
      title: "Total Overdue",
      value: summary?.total_overdue || 0,
      color: danger.base,
      bg: danger[10],
    },
  ];

  const isLoading = summaryLoading || payoutsLoading;

  return (
    <SafeAreaView className="flex-1 bg-white" edges={["top"]}>
      <View className="px-6 mb-4">
        <BackButtonTitle title={tran("ROI Received")} />
      </View>

      <ScrollView
        refreshControl={<RefreshControl refreshing={false} onRefresh={onRefresh} tintColor={primary.base} colors={[primary.base]} />}
        className="flex-1"
        contentContainerStyle={{ paddingHorizontal: 24, paddingBottom: 40 }}
      >
        {/* Stats Grid */}
        <View className="flex-row flex-wrap gap-3 justify-between">
          {stats.map((stat, index) => (
            <View key={index} className="rounded-2xl w-[48%] p-4 border border-slate-50 shadow-sm shadow-slate-200" style={{ backgroundColor: "white" }}>
              <View className="flex-row items-center justify-between mb-3">
                <View className="w-10 h-10 rounded-xl items-center justify-center" style={{ backgroundColor: stat.bg }}>
                  <stat.icon color={stat.color} size={20} weight="bold" />
                </View>
              </View>
              <View>
                <Text className="text-[11px] font-manrope-bold text-slate-400 uppercase tracking-widest mb-1">{tran(stat.title)}</Text>
                <Text className="text-xl font-manrope-extrabold text-slate-900">
                  {currency.symbol}
                  {translateNumber(stat.value)}
                </Text>
              </View>
            </View>
          ))}
        </View>

        {/* History Section */}
        <View className="pt-10">
          <View className="flex-row items-center justify-between mb-6">
            <View>
              <Text className="text-xl font-manrope-extrabold text-slate-900">{tran("Payment History")}</Text>
              <Text className="text-sm font-manrope text-slate-500 mt-1">{tran("Track your latest returns")}</Text>
            </View>
            <View className="w-10 h-10 rounded-full bg-slate-50 items-center justify-center">
              <ClockIcon size={20} color="#64748b" weight="bold" />
            </View>
          </View>

          {isLoading ? (
            <View className="py-20 items-center justify-center">
              <ActivityIndicator color={primary.base} size="large" />
            </View>
          ) : payouts?.data?.length > 0 ? (
            <View className="gap-4">
              {payouts.data.map((item: any) => (
                <View
                  key={item.id}
                  className="bg-white border border-slate-100 rounded-2xl p-4 flex-row items-center gap-4 relative overflow-hidden"
                  style={{
                    shadowColor: "#000",
                    shadowOffset: { width: 0, height: 2 },
                    shadowOpacity: 0.05,
                    shadowRadius: 10,
                    elevation: 2,
                  }}
                >
                  <View className="absolute left-0 top-0 bottom-0 w-1.5" style={{ backgroundColor: success.base }} />

                  <View className="flex-1">
                    <View className="flex-row justify-between items-start mb-2">
                      <View className="flex-1 mr-2">
                        <Text className="text-[10px] font-manrope-bold text-slate-400 uppercase tracking-widest leading-none mb-1">{tran("Project")}</Text>
                        <Text className="text-base font-manrope-bold text-slate-900" numberOfLines={1}>
                          {item?.project?.title}
                        </Text>
                      </View>
                      <View className="px-3 py-1 rounded-full" style={{ backgroundColor: success[10] }}>
                        <Text className="text-[10px] font-manrope-extrabold uppercase tracking-widest" style={{ color: success.base }}>
                          {tran("Paid")}
                        </Text>
                      </View>
                    </View>

                    <View className="flex-row justify-between items-end mt-2 pt-3 border-t border-slate-50">
                      <View>
                        <Text className="text-[10px] font-manrope-bold text-slate-400 uppercase tracking-widest leading-none mb-1">{tran("Amount")}</Text>
                        <Text className="text-lg font-manrope-extrabold text-slate-900">
                          {currency.symbol}
                          {translateNumber(item?.amount)}
                        </Text>
                      </View>
                      <View className="items-end">
                        <Text className="text-[10px] font-manrope-bold text-slate-400 uppercase tracking-widest leading-none mb-1">{tran("Paid Date")}</Text>
                        <Text className="text-sm font-manrope-medium text-slate-500">{formatDate(item?.paid_at)}</Text>
                      </View>
                    </View>
                  </View>
                </View>
              ))}
            </View>
          ) : (
            <View className="py-20 items-center justify-center bg-slate-50 rounded-3xl border border-dotted border-slate-200">
              <View className="w-16 h-16 rounded-full bg-slate-100 items-center justify-center mb-4">
                <WalletIcon size={32} color="#cbd5e1" weight="duotone" />
              </View>
              <Text className="text-lg font-manrope-bold text-slate-400">{tran("No Payouts Yet")}</Text>
              <Text className="text-sm font-manrope text-slate-400 mt-1 max-w-[200px] text-center">{tran("Your earnings will automatically show up here once paid.")}</Text>
            </View>
          )}
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}
