import { useTranslation } from "react-i18next";
import {
  ComposedChart,
  Bar,
  Line,
  XAxis,
  YAxis,
  Tooltip,
  Legend,
  CartesianGrid,
  ReferenceLine,
  ResponsiveContainer,
} from "recharts";
import type { CartesMonthFlow } from "../../../shared/types";

export interface IncomeExpenseOverlayChartProps {
  flow: CartesMonthFlow[];
}

function formatCurrency(amount: number, language: string): string {
  return new Intl.NumberFormat(language === "fr" ? "fr-CA" : "en-CA", {
    style: "currency",
    currency: "CAD",
    maximumFractionDigits: 0,
  }).format(amount);
}

function formatMonthShort(month: string, language: string): string {
  const [y, m] = month.split("-").map(Number);
  if (!Number.isFinite(y) || !Number.isFinite(m)) return month;
  return new Intl.DateTimeFormat(language === "fr" ? "fr-CA" : "en-CA", {
    month: "short",
    year: "2-digit",
  }).format(new Date(y, m - 1, 1));
}

export default function IncomeExpenseOverlayChart({ flow }: IncomeExpenseOverlayChartProps) {
  const { t, i18n } = useTranslation();

  if (flow.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>
    );
  }

  const data = flow.map((p) => ({
    ...p,
    label: formatMonthShort(p.month, i18n.language),
  }));

  return (
    <div className="bg-[var(--card)] border border-[var(--border)] rounded-xl p-4">
      <div className="text-sm font-medium text-[var(--foreground)] mb-3">
        {t("reports.cartes.flowChartTitle")}
      </div>
      <ResponsiveContainer width="100%" height={260}>
        <ComposedChart data={data} margin={{ top: 10, right: 20, bottom: 0, left: 0 }}>
          <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />
          <XAxis dataKey="label" stroke="var(--muted-foreground)" fontSize={11} />
          <YAxis
            stroke="var(--muted-foreground)"
            fontSize={11}
            tickFormatter={(v) => formatCurrency(v, i18n.language)}
            width={80}
          />
          <Tooltip
            formatter={(value) =>
              typeof value === "number" ? formatCurrency(value, i18n.language) : String(value)
            }
            contentStyle={{
              backgroundColor: "var(--card)",
              border: "1px solid var(--border)",
              borderRadius: "0.5rem",
            }}
          />
          <Legend
            wrapperStyle={{ paddingTop: 8, fontSize: 12, color: "var(--muted-foreground)" }}
          />
          <ReferenceLine y={0} stroke="var(--border)" />
          <Bar dataKey="income" name={t("reports.cartes.income")} fill="var(--positive)" />
          <Bar dataKey="expenses" name={t("reports.cartes.expenses")} fill="var(--negative)" />
          <Line
            type="monotone"
            dataKey="net"
            name={t("reports.cartes.net")}
            stroke="var(--primary)"
            strokeWidth={2}
            dot={{ r: 2 }}
            isAnimationActive={false}
          />
        </ComposedChart>
      </ResponsiveContainer>
    </div>
  );
}
