"use client";

import { useState, type ComponentType } from "react";
import { BarChart3, LineChart as LineIcon, PieChart as PieIcon, Send } from "lucide-react";
import {
  LineChart, Line, BarChart, Bar, PieChart, Pie, Cell,
  XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
} from "recharts";
import { useTranslation } from "@/hooks/useTranslation";
import { ButtonLink } from "@/components/common/Button";
import { cn } from "@/lib/utils";

export interface ActivitySeries {
  key: string;
  label: string;
  color: string;
  values: number[];
}

type ChartType = "line" | "bar" | "pie";

const CHART_TYPES: { type: ChartType; icon: ComponentType<{ className?: string }>; key: string }[] = [
  { type: "line", icon: LineIcon, key: "chartLine" },
  { type: "bar", icon: BarChart3, key: "chartBar" },
  { type: "pie", icon: PieIcon, key: "chartPie" },
];

interface TooltipPayload {
  color: string;
  name: string;
  value: number;
  dataKey: string;
}

function ChartTooltip({ active, payload, label }: { active?: boolean; payload?: TooltipPayload[]; label?: string }) {
  if (!active || !payload?.length) return null;
  return (
    <div className="rounded-xl border border-white/10 bg-slate-900/95 p-3 shadow-lg backdrop-blur-sm">
      <p className="mb-1.5 text-xs font-semibold text-slate-400">{label}</p>
      {payload.map((p) => (
        <div key={p.dataKey} className="flex items-center gap-2 text-xs">
          <span className="inline-block h-2 w-2 rounded-full" style={{ background: p.color }} />
          <span className="text-slate-400">{p.name}:</span>
          <span className="font-bold text-white">{p.value.toLocaleString()}</span>
        </div>
      ))}
    </div>
  );
}

/** Dark-styled activity chart for the dashboard hero — pattern shared with agent/dashboard's
 * ActivityChart, restyled here since this one always sits on the banner's fixed-dark surface
 * rather than a site-theme-reactive card. */
export function DashboardActivityChart({ categories, series }: { categories: string[]; series: ActivitySeries[] }) {
  const { t, dir } = useTranslation();
  const [chartType, setChartType] = useState<ChartType>("line");

  const data = categories.map((cat, i) => ({
    name: cat,
    ...Object.fromEntries(series.map((s) => [s.key, s.values[i] ?? 0])),
  }));

  const pieData = series.map((s) => ({
    name: s.label,
    value: s.values.reduce((a, b) => a + b, 0),
    color: s.color,
  }));

  const hasData = pieData.some((d) => d.value > 0);

  const axisTick = { fill: "#94a3b8", fontSize: 11 };
  const gridProps = { stroke: "rgba(148,163,184,0.15)", strokeDasharray: "3 3" as const };
  const margin = { top: 5, right: 8, left: -20, bottom: 0 };

  return (
    <div className="flex h-full flex-col">
      <div className="mb-4 flex shrink-0 gap-1 rounded-xl bg-slate-100 p-1 dark:bg-white/5">
        {CHART_TYPES.map(({ type, icon: Icon, key }) => (
          <button
            key={type}
            type="button"
            onClick={() => setChartType(type)}
            className={cn(
              "flex flex-1 items-center justify-center gap-1.5 rounded-lg py-1.5 text-xs font-semibold transition-all",
              chartType === type
                ? "bg-white text-slate-900 shadow-2xs dark:bg-white/10 dark:text-white dark:shadow-none"
                : "text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200",
            )}
          >
            <Icon className="icon-sm" />
            <span className="hidden sm:inline">{t(`agent.dashboard.${key}`)}</span>
          </button>
        ))}
      </div>

      {!hasData ? (
        <div className="flex min-h-[340px] flex-1 flex-col items-center justify-center gap-3 px-6 text-center">
          <div>
            <p className="text-sm font-semibold text-white">{t("agent.dashboard.noActivityData")}</p>
            <p className="mt-1 text-xs text-slate-400">{t("agent.dashboard.noActivityDataDesc")}</p>
          </div>
          <ButtonLink href="/send" size="sm" className="mt-1">
            <Send className={cn("icon-sm", dir === "rtl" && "[transform:scaleX(-1)]")} />
            {t("agent.dashboard.sendRemittance")}
          </ButtonLink>
        </div>
      ) : (
      <>
      <div className="h-[340px]">
        <ResponsiveContainer width="100%" height="100%">
        {chartType === "line" ? (
          <LineChart data={data} margin={margin}>
            <CartesianGrid {...gridProps} />
            <XAxis dataKey="name" tick={axisTick} axisLine={false} tickLine={false} />
            <YAxis tick={axisTick} axisLine={false} tickLine={false} />
            <Tooltip content={<ChartTooltip />} />
            {series.map((s) => (
              <Line key={s.key} type="monotone" dataKey={s.key} name={s.label} stroke={s.color} strokeWidth={2} dot={{ r: 3, fill: s.color, strokeWidth: 0 }} activeDot={{ r: 5, strokeWidth: 0 }} />
            ))}
          </LineChart>
        ) : chartType === "bar" ? (
          <BarChart data={data} margin={margin}>
            <CartesianGrid {...gridProps} />
            <XAxis dataKey="name" tick={axisTick} axisLine={false} tickLine={false} />
            <YAxis tick={axisTick} axisLine={false} tickLine={false} />
            <Tooltip content={<ChartTooltip />} />
            {series.map((s) => (
              <Bar key={s.key} dataKey={s.key} name={s.label} fill={s.color} radius={[4, 4, 0, 0]} fillOpacity={0.9} />
            ))}
          </BarChart>
        ) : (
          <PieChart>
            <Pie data={pieData} cx="50%" cy="50%" innerRadius={45} outerRadius={72} dataKey="value" paddingAngle={3}>
              {pieData.map((entry) => (
                <Cell key={entry.name} fill={entry.color} fillOpacity={0.9} stroke="none" />
              ))}
            </Pie>
            <Tooltip content={<ChartTooltip />} />
          </PieChart>
        )}
        </ResponsiveContainer>
      </div>

      <div className="mt-3 flex shrink-0 flex-wrap items-center justify-center gap-x-4 gap-y-1.5">
        {series.map((s) => (
          <div key={s.key} className="flex items-center gap-1.5">
            <span className="inline-block h-2 w-2 rounded-full" style={{ background: s.color }} />
            <span className="text-2xs font-medium text-slate-500 dark:text-slate-400">{s.label}</span>
          </div>
        ))}
      </div>
      </>
      )}
    </div>
  );
}
