import { useTranslation } from "react-i18next";
import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
} from "recharts";
import type { CategoryZoomEvolutionPoint } from "../../shared/types";

export interface CategoryEvolutionChartProps {
  data: CategoryZoomEvolutionPoint[];
  color?: string;
}

function formatMonth(month: string): string {
  const [year, m] = month.split("-");
  const date = new Date(Number(year), Number(m) - 1);
  return date.toLocaleDateString("default", { month: "short", year: "2-digit" });
}

export default function CategoryEvolutionChart({
  data,
  color = "var(--primary)",
}: CategoryEvolutionChartProps) {
  const { t, i18n } = useTranslation();

  if (data.length === 0) {
    return (
      <div className="bg-[var(--card)] border border-[var(--border)] rounded-xl p-6 text-center text-[var(--muted-foreground)] italic">
        {t("reports.empty.noData")}
      </div>
    );
  }

  return (
    <div className="bg-[var(--card)] border border-[var(--border)] rounded-xl p-4">
      <h3 className="text-sm font-semibold mb-2">{t("reports.category.evolution")}</h3>
      <ResponsiveContainer width="100%" height={200}>
        <AreaChart data={data} margin={{ top: 10, right: 20, bottom: 10, left: 10 }}>
          <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" />
          <XAxis
            dataKey="month"
            tickFormatter={formatMonth}
            stroke="var(--muted-foreground)"
            fontSize={11}
          />
          <YAxis
            stroke="var(--muted-foreground)"
            fontSize={11}
            tickFormatter={(v: number) =>
              new Intl.NumberFormat(i18n.language === "fr" ? "fr-CA" : "en-CA", {
                style: "currency",
                currency: "CAD",
                maximumFractionDigits: 0,
              }).format(v)
            }
          />
          <Tooltip
            formatter={(value) =>
              typeof value === "number"
                ? new Intl.NumberFormat(i18n.language === "fr" ? "fr-CA" : "en-CA", {
                    style: "currency",
                    currency: "CAD",
                  }).format(value)
                : String(value)
            }
            labelFormatter={(label) => (typeof label === "string" ? formatMonth(label) : String(label ?? ""))}
            contentStyle={{
              backgroundColor: "var(--card)",
              border: "1px solid var(--border)",
              borderRadius: "0.5rem",
            }}
          />
          <Area type="monotone" dataKey="total" stroke={color} fill={color} fillOpacity={0.2} />
        </AreaChart>
      </ResponsiveContainer>
    </div>
  );
}
