// src/components/keywords/research/coverage-matrix.tsx
"use client";

import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Flag } from "@/components/ui/flag";
import type { TargetStatus, TargetsState } from "@/lib/keywords/targets";
import type { Keyword } from "@/lib/keywords/types";
import { TargetStatusBadge } from "./target-status-badge";

const MENU: { value: TargetStatus | null; label: string }[] = [
  { value: null, label: "— non ciblé" },
  { value: "candidate", label: "candidat" },
  { value: "planned", label: "planifié" },
  { value: "live", label: "en ligne" },
];

function Cell({
  status,
  position,
  term,
  countryLabel,
  onSet,
}: {
  status: TargetStatus | undefined;
  position?: number;
  term: string;
  countryLabel: string;
  onSet: (s: TargetStatus | null) => void;
}) {
  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <button
          type="button"
          className="inline-flex min-w-16 flex-col items-center gap-0.5 rounded px-1 py-0.5 hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
          aria-label={`${term} — ${countryLabel} : ${status ?? "non ciblé"}${
            position != null ? `, position ${position.toFixed(1)}` : ""
          }`}
        >
          {status ? (
            <TargetStatusBadge status={status} />
          ) : (
            <span className="text-muted-foreground">—</span>
          )}
          {position != null ? (
            <span className="text-muted-foreground text-xs tabular-nums">
              p. {position.toFixed(1)}
            </span>
          ) : null}
        </button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="start">
        {MENU.map((m) => (
          <DropdownMenuItem key={m.label} onSelect={() => onSet(m.value)}>
            {m.label}
          </DropdownMenuItem>
        ))}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}

export function CoverageMatrix({
  keywords,
  countries,
  targets,
  onSetCell,
  emptyLabel,
  /** True when the server-side fetch was capped (2 000 lignes, P1) — shows a
   *  banner inviting the user to narrow the filters instead of silently
   *  hiding the rest of the matching set. */
  truncated,
}: {
  keywords: Keyword[];
  countries: string[];
  targets: TargetsState;
  onSetCell: (
    keywordId: string,
    country: string,
    status: TargetStatus | null,
  ) => void;
  emptyLabel?: string;
  truncated?: boolean;
}) {
  if (keywords.length === 0)
    return (
      <div className="rounded-md border p-8 text-center text-muted-foreground">
        {emptyLabel ?? "Aucun keyword pour ce site."}
      </div>
    );

  return (
    <div className="flex flex-col gap-2">
      {truncated ? (
        <div className="rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-amber-700 text-sm dark:text-amber-400">
          Affiche les 2 000 premiers résultats — affinez les filtres pour voir
          le reste.
        </div>
      ) : null}
      <div className="overflow-x-auto rounded-md border">
        <table className="w-full caption-bottom text-sm">
          <caption className="sr-only">
            Couverture des mots-clés par pays cible
          </caption>
          <thead>
            <tr className="border-b">
              <th scope="col" className="px-3 py-2 text-left font-medium">
                Terme
              </th>
              {countries.map((code) => (
                <th
                  key={code}
                  scope="col"
                  className="px-3 py-2 text-left font-medium"
                >
                  <Flag code={code} /> {code}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {countries.length === 0 ? (
              <tr className="border-b last:border-0">
                <td className="px-3 py-4 text-muted-foreground">
                  Configure les pays cibles de ce site (Settings).
                </td>
              </tr>
            ) : (
              keywords.map((k) => (
                <tr key={k.id} className="border-b last:border-0">
                  <th scope="row" className="px-3 py-2 text-left font-medium">
                    {k.term}
                  </th>
                  {countries.map((code) => (
                    <td key={code} className="px-3 py-2">
                      <Cell
                        status={targets[k.id]?.[code]}
                        position={k.gscByCountry?.[code]?.position}
                        term={k.term}
                        countryLabel={code}
                        onSet={(s) => onSetCell(k.id, code, s)}
                      />
                    </td>
                  ))}
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
