import AppText from "@/components/ui/app-text";
import { useGetQuery } from "@/hooks/mutate/useGetQuery";
import { useColor } from "@/hooks/useColor";
import { useCurrency } from "@/hooks/useCurrency";
import { useTranslations } from "@/providers/TranslationProviders";
import { ChartDonutIcon, ChartLineUpIcon } from "phosphor-react-native";
import React, { useMemo, useState } from "react";
import { ActivityIndicator, Pressable, View, useWindowDimensions } from "react-native";
import { LineChart, PieChart } from "react-native-gifted-charts";

export default function DashboardCharts() {
  const { primary, success, danger } = useColor();
  const { currency } = useCurrency();
  const { tran, translateNumber } = useTranslations();
  const { width: screenWidth } = useWindowDimensions();

  const [term, setTerm] = useState<"daily" | "monthly" | "yearly">("monthly");
  const [activeSeriesIndex, setActiveSeriesIndex] = useState(0);

  const { data: analytics, isLoading: isAnalyticsLoading } = useGetQuery({
    url: `/client/transaction/summary/${term}`,
  });

  const { data: portfolio, isLoading: isPortfolioLoading } = useGetQuery({
    url: "/client/summary",
  });

  const isLoading = isAnalyticsLoading || isPortfolioLoading;

  const seriesColorMap: Record<string, string> = useMemo(
    () => ({
      Investment: primary.base,
      "ROI Received": success.base,
      Deposit: "#f59e0b",
      Withdrawal: danger.base,
    }),
    [primary.base, success.base, danger.base],
  );

  const seriesList = useMemo(() => {
    return (analytics?.series ?? []).map((s: any) => ({
      name: s.name,
      translatedName: tran(s.name),
      data: (s.data ?? []).map((v: any) => Number(v) || 0),
      color: seriesColorMap[s.name] || primary.base,
    }));
  }, [analytics, tran, seriesColorMap, primary.base]);

  const labels = useMemo(() => {
    return (analytics?.labels ?? []).map((label: string) => translateNumber(tran(label)));
  }, [analytics, tran, translateNumber]);

  const activeSeries = seriesList[activeSeriesIndex] ?? seriesList[0];

  const lineChartData = useMemo(() => {
    if (!activeSeries) return [];
    return activeSeries.data.map((value: number, idx: number) => ({
      value,
      label: labels[idx] ?? "",
      dataPointText: "",
    }));
  }, [activeSeries, labels]);

  const maxLineValue = useMemo(() => {
    const vals = lineChartData.map((d: any) => d.value);
    const max = vals.length ? Math.max(...vals) : 0;
    return max > 0 ? Math.ceil(max * 1.2) : 100;
  }, [lineChartData]);

  // Portfolio data
  const portfolioSummary = portfolio?.portfolio_summary;
  const totalShares = portfolioSummary?.total_shares || 1;

  const portfolioMetrics = useMemo(
    () => [
      { name: "Portfolio Value", value: portfolioSummary?.portfolio_value ?? 0, color: "#6366f1", isCurrency: true },
      { name: "Total Projects", value: portfolioSummary?.total_projects ?? 0, color: "#8b5cf6" },
      { name: "Active Shares", value: portfolioSummary?.active_shares ?? 0, color: "#10b981", isShare: true },
      { name: "Listed Shares", value: portfolioSummary?.listed_shares ?? 0, color: "#3b82f6", isShare: true },
      { name: "Sold Shares", value: portfolioSummary?.sold_shares ?? 0, color: "#f59e0b", isShare: true },
    ],
    [portfolioSummary],
  );

  const pieChartData = useMemo(() => {
    const total = portfolioMetrics.reduce((sum, m) => sum + (Number(m.value) || 0), 0);
    if (total <= 0) {
      return [{ value: 1, color: "#e2e8f0" }];
    }
    return portfolioMetrics
      .filter((m) => Number(m.value) > 0)
      .map((m) => ({ value: Number(m.value), color: m.color }));
  }, [portfolioMetrics]);

  const activityPercentage = totalShares > 0 ? Math.round((((portfolioSummary?.active_shares ?? 0) + (portfolioSummary?.listed_shares ?? 0)) / totalShares) * 100) : 0;

  const getActivityData = () => {
    if (activityPercentage === 0) return { label: "Inactive", classes: "text-slate-500 bg-slate-100" };
    if (activityPercentage < 30) return { label: "Low", classes: "text-red-600 bg-red-50" };
    if (activityPercentage < 60) return { label: "Moderate", classes: "text-amber-600 bg-amber-50" };
    if (activityPercentage < 80) return { label: "Active", classes: "text-blue-600 bg-blue-50" };
    return { label: "Highly Active", classes: "text-emerald-600 bg-emerald-50" };
  };

  const activityData = getActivityData();

  if (isLoading) {
    return (
      <View className="flex-1 items-center justify-center py-20 min-h-[300px]">
        <ActivityIndicator color={primary.base} size="small" />
      </View>
    );
  }

  const lineChartWidth = screenWidth - 80;

  return (
    <View className="gap-y-6 pt-6">
      {/* Area Chart Section */}
      <View className="bg-white rounded-[32px] p-6 border border-slate-50 shadow-sm shadow-slate-100">
        <View className="flex-row items-center justify-between mb-8">
          <View className="flex-row items-center gap-3.5">
            <View className="w-11 h-11 bg-indigo-50 rounded-2xl items-center justify-center">
              <ChartLineUpIcon color="#6366f1" size={24} weight="bold" />
            </View>
            <View>
              <AppText className="font-manrope-extrabold text-[17px] text-slate-800 leading-tight">{tran("Investment Analytics")}</AppText>
              <AppText className="text-slate-400 text-[11px] font-manrope-bold uppercase tracking-wider">{tran("Returns vs Investments")}</AppText>
            </View>
          </View>
        </View>

        {/* Term Filters */}
        <View className="flex-row items-center gap-1 bg-slate-50 rounded-xl p-1 mb-4 self-start">
          {[
            { label: "Daily", value: "daily" },
            { label: "Monthly", value: "monthly" },
            { label: "Yearly", value: "yearly" },
          ].map((btn) => {
            const isActive = term === btn.value;
            return (
              <Pressable
                key={btn.value}
                onPress={() => setTerm(btn.value as any)}
                className="px-4 py-2 rounded-lg"
                style={{
                  backgroundColor: isActive ? "white" : "transparent",
                  shadowColor: isActive ? "#000" : "transparent",
                  shadowOffset: { width: 0, height: 1 },
                  shadowOpacity: isActive ? 0.05 : 0,
                  shadowRadius: 2,
                  elevation: isActive ? 1 : 0,
                }}
              >
                <AppText className="text-[12px] font-manrope-bold" style={{ color: isActive ? "#4f46e5" : "#64748b" }}>
                  {tran(btn.label)}
                </AppText>
              </Pressable>
            );
          })}
        </View>

        {/* Series picker */}
        {seriesList.length > 1 && (
          <View className="flex-row flex-wrap gap-2 mb-4">
            {seriesList.map((s: any, idx: number) => {
              const isActive = activeSeriesIndex === idx;
              return (
                <Pressable
                  key={s.name}
                  onPress={() => setActiveSeriesIndex(idx)}
                  className="flex-row items-center gap-1.5 px-3 py-1.5 rounded-full border"
                  style={{
                    backgroundColor: isActive ? s.color : "transparent",
                    borderColor: isActive ? s.color : "#e2e8f0",
                  }}
                >
                  <View className="size-2 rounded-full" style={{ backgroundColor: isActive ? "white" : s.color }} />
                  <AppText className="text-[11px] font-manrope-bold" style={{ color: isActive ? "white" : "#64748b" }}>
                    {s.translatedName}
                  </AppText>
                </Pressable>
              );
            })}
          </View>
        )}

        {/* Line Chart */}
        {lineChartData.length > 0 ? (
          <View>
            <LineChart
              areaChart
              data={lineChartData}
              width={lineChartWidth}
              height={220}
              color={activeSeries?.color ?? primary.base}
              startFillColor={activeSeries?.color ?? primary.base}
              endFillColor={activeSeries?.color ?? primary.base}
              startOpacity={0.4}
              endOpacity={0.05}
              thickness={3}
              curved
              hideDataPoints={false}
              dataPointsColor={activeSeries?.color ?? primary.base}
              dataPointsRadius={4}
              maxValue={maxLineValue}
              noOfSections={4}
              yAxisColor="transparent"
              xAxisColor="#f1f5f9"
              rulesColor="#f8fafc"
              rulesType="solid"
              yAxisTextStyle={{ color: "#94a3b8", fontSize: 10 }}
              xAxisLabelTextStyle={{ color: "#94a3b8", fontSize: 10 }}
              initialSpacing={10}
              spacing={Math.max(30, Math.floor((lineChartWidth - 40) / Math.max(lineChartData.length, 1)))}
              formatYLabel={(val: string) => {
                const n = Number(val);
                if (n >= 1000) return `${currency.symbol}${(n / 1000).toFixed(1)}k`;
                return `${currency.symbol}${Math.round(n)}`;
              }}
            />
          </View>
        ) : (
          <View className="h-[220px] items-center justify-center">
            <AppText className="text-slate-400 font-manrope-medium">{tran("No data available")}</AppText>
          </View>
        )}
      </View>

      {/* Donut Chart Section */}
      <View className="bg-white rounded-[32px] p-6 border border-slate-50 shadow-sm shadow-slate-100">
        <View className="flex-row items-center gap-3.5 mb-8">
          <View className="w-11 h-11 bg-emerald-50 rounded-2xl items-center justify-center">
            <ChartDonutIcon color="#10b981" size={24} weight="bold" />
          </View>
          <View>
            <AppText className="font-manrope-extrabold text-[17px] text-slate-800 leading-tight">{tran("Portfolio Distribution")}</AppText>
            <AppText className="text-slate-400 text-[11px] font-manrope-bold uppercase tracking-wider">{tran("Share Transaction status")}</AppText>
          </View>
        </View>

        <View className="items-center justify-center mb-6">
          <PieChart
            donut
            data={pieChartData}
            radius={100}
            innerRadius={65}
            innerCircleColor="#ffffff"
            centerLabelComponent={() => (
              <View className="items-center">
                <AppText className="text-[11px] font-manrope-bold text-slate-400 uppercase tracking-wider">{tran("Shares")}</AppText>
                <AppText className="text-2xl font-manrope-extrabold text-slate-900">{translateNumber(totalShares)}</AppText>
              </View>
            )}
          />
        </View>

        {/* Legend */}
        <View className="gap-y-3.5 mb-8">
          {portfolioMetrics.map((item) => (
            <View key={item.name} className="flex-row items-center justify-between">
              <View className="flex-row items-center gap-x-2.5">
                <View className="size-2 rounded-full" style={{ backgroundColor: item.color }} />
                <AppText className="text-[13px] text-slate-500 font-manrope-medium">{tran(item.name)}</AppText>
              </View>
              <View className="flex-row items-center gap-x-2.5">
                <AppText className="text-[14px] font-manrope-bold text-slate-800">
                  {item.isCurrency ? currency.symbol : ""}
                  {translateNumber(item.value.toLocaleString())}
                  {item.isShare ? ` ${tran("Shares")}` : ""}
                </AppText>
                {item.isShare && (
                  <AppText className="text-[11px] text-slate-400 font-manrope-bold w-10 text-right">
                    {totalShares > 0 ? Math.round((item.value / totalShares) * 100) : 0}%
                  </AppText>
                )}
              </View>
            </View>
          ))}
        </View>

        {/* Activity Indicator Bar */}
        <View className="bg-slate-50 rounded-2xl p-4">
          <View className="flex-row items-center justify-between mb-4">
            <AppText className="text-[13px] font-manrope-bold text-slate-600">{tran("Activity Level")}</AppText>
            <View className={`px-2.5 py-1 rounded-full ${activityData.classes}`}>
              <AppText className="text-[10px] font-manrope-extrabold uppercase tracking-wide">{tran(activityData.label)}</AppText>
            </View>
          </View>
          <View className="h-1.5 w-full bg-slate-200 rounded-full overflow-hidden">
            <View
              className="h-full rounded-full"
              style={{
                width: `${activityPercentage}%`,
                backgroundColor: activityPercentage < 30 ? "#ef4444" : activityPercentage < 70 ? "#f59e0b" : "#10b981",
              }}
            />
          </View>
        </View>
      </View>
    </View>
  );
}
