import { useState } from "react";
import { useTranslation } from "react-i18next";
import type { HighlightMover } from "../../shared/types";

type SortKey = "categoryName" | "previous" | "current" | "deltaAbs" | "deltaPct";

export interface HighlightsTopMoversTableProps {
  movers: HighlightMover[];
}

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

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

function formatPct(pct: number | null, language: string): string {
  if (pct === null) return "—";
  return new Intl.NumberFormat(language === "fr" ? "fr-CA" : "en-CA", {
    style: "percent",
    maximumFractionDigits: 1,
    signDisplay: "always",
  }).format(pct / 100);
}

export default function HighlightsTopMoversTable({ movers }: HighlightsTopMoversTableProps) {
  const { t, i18n } = useTranslation();
  const [sortKey, setSortKey] = useState<SortKey>("deltaAbs");
  const [sortDir, setSortDir] = useState<"asc" | "desc">("desc");

  const sorted = [...movers].sort((a, b) => {
    let cmp = 0;
    switch (sortKey) {
      case "categoryName":
        cmp = a.categoryName.localeCompare(b.categoryName);
        break;
      case "previous":
        cmp = a.previousAmount - b.previousAmount;
        break;
      case "current":
        cmp = a.currentAmount - b.currentAmount;
        break;
      case "deltaAbs":
        cmp = Math.abs(a.deltaAbs) - Math.abs(b.deltaAbs);
        break;
      case "deltaPct":
        cmp = (a.deltaPct ?? 0) - (b.deltaPct ?? 0);
        break;
    }
    return sortDir === "asc" ? cmp : -cmp;
  });

  function toggleSort(key: SortKey) {
    if (sortKey === key) {
      setSortDir((d) => (d === "asc" ? "desc" : "asc"));
    } else {
      setSortKey(key);
      setSortDir("desc");
    }
  }

  const headerCell = (key: SortKey, label: string, align: "left" | "right") => (
    <th
      onClick={() => toggleSort(key)}
      className={`${align === "right" ? "text-right" : "text-left"} px-3 py-2 font-medium text-[var(--muted-foreground)] cursor-pointer hover:text-[var(--foreground)] select-none`}
    >
      {label}
      {sortKey === key && <span className="ml-1">{sortDir === "asc" ? "▲" : "▼"}</span>}
    </th>
  );

  return (
    <div className="bg-[var(--card)] border border-[var(--border)] rounded-xl overflow-hidden">
      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-[var(--border)]">
              {headerCell("categoryName", t("reports.highlights.category"), "left")}
              {headerCell("previous", t("reports.highlights.previousAmount"), "right")}
              {headerCell("current", t("reports.highlights.currentAmount"), "right")}
              {headerCell("deltaAbs", t("reports.highlights.variationAbs"), "right")}
              {headerCell("deltaPct", t("reports.highlights.variationPct"), "right")}
            </tr>
          </thead>
          <tbody>
            {sorted.length === 0 ? (
              <tr>
                <td colSpan={5} className="px-3 py-4 text-center text-[var(--muted-foreground)] italic">
                  {t("reports.empty.noData")}
                </td>
              </tr>
            ) : (
              sorted.map((mover) => (
                <tr
                  key={`${mover.categoryId ?? "uncat"}-${mover.categoryName}`}
                  className="border-b border-[var(--border)] last:border-0 hover:bg-[var(--muted)]/40"
                >
                  <td className="px-3 py-2">
                    <span className="flex items-center gap-2">
                      <span
                        className="w-2 h-2 rounded-full flex-shrink-0"
                        style={{ backgroundColor: mover.categoryColor }}
                      />
                      {mover.categoryName}
                    </span>
                  </td>
                  <td className="px-3 py-2 text-right tabular-nums">
                    {formatCurrency(mover.previousAmount, i18n.language)}
                  </td>
                  <td className="px-3 py-2 text-right tabular-nums">
                    {formatCurrency(mover.currentAmount, i18n.language)}
                  </td>
                  <td
                    className="px-3 py-2 text-right tabular-nums font-medium"
                    style={{
                      color:
                        mover.deltaAbs >= 0 ? "var(--negative, #ef4444)" : "var(--positive, #10b981)",
                    }}
                  >
                    {formatSignedCurrency(mover.deltaAbs, i18n.language)}
                  </td>
                  <td
                    className="px-3 py-2 text-right tabular-nums"
                    style={{
                      color:
                        mover.deltaAbs >= 0 ? "var(--negative, #ef4444)" : "var(--positive, #10b981)",
                    }}
                  >
                    {formatPct(mover.deltaPct, i18n.language)}
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
