// Ligne de paire en grille 3-col : [checks_col 78px | xlsx_cell | db_cell].
// Calque exact (couleurs hex incluses) de
//   coolcare-app/public/admin/report_templates_review.php (CSS)
//   coolcare-app/public/js/admin/report_templates_review.js (renderPairRow)

import type { DiffPair, PairCategory } from "@/lib/api/types";
import type { PairChoice } from "@/lib/api/report-templates";
import { StepCell } from "./step-cell";

function isProtectedPair(pair: DiffPair): boolean {
  return pair.category === "db_only_volontaire";
}

// Fond du cell XLSX : vert pâle (xlsx-only) seulement quand le step XLSX
// existe sans contrepartie BDD. Sinon fond neutre (laissé au parent).
function xlsxCellClass(pair: DiffPair): string {
  if (!pair.xlsx) return "";
  if (!pair.db && pair.category === "xlsx_only") {
    return "bg-[#dcfce7]";
  }
  return "";
}

// Fond du cell BDD : violet pâle + border-left accent pour volontaire
// (verrou migration_id), bleu pâle pour orphelin, sinon neutre.
function dbCellClass(pair: DiffPair): string {
  if (!pair.db) return "";
  if (pair.xlsx) return "";
  if (isProtectedPair(pair)) {
    return "bg-[#ede9fe] border-l-[3px] border-l-[#7c3aed]";
  }
  if (pair.category === "db_only_orphan") {
    return "bg-[#dbeafe]";
  }
  return "";
}

export function PairRow({
  pair,
  isChild = false,
  selectedChoice,
  onChoiceChange,
  pairKey,
}: {
  pair: DiffPair;
  isChild?: boolean;
  selectedChoice: PairChoice;
  onChoiceChange: (uid: string, choice: PairChoice) => void;
  pairKey: string;
}) {
  const protectedPair = isProtectedPair(pair);
  const hasXlsx = pair.xlsx !== null;
  const hasDb = pair.db !== null;
  const effectiveChoice: PairChoice = protectedPair ? "db" : selectedChoice;
  const radioName = `pair-${pairKey}`;

  // Backgrounds : enfant = neutral-50 + checks-col gray-100, parent = checks-col gray-50.
  // Override violet si paire protégée (lock migration_id).
  const rowBg = isChild ? "bg-[#fafafa]" : "";
  const checksBg = protectedPair
    ? "bg-[#ede9fe]"
    : isChild
      ? "bg-[#f3f4f6]"
      : "bg-[#f9fafb]";

  // Marqueur ⚠ pour common_divergent : on affiche les NOMS des champs
  // divergents (kind, options, is_required…) en rouge, pas un compteur.
  const showDivergentMarker =
    pair.category === "common_divergent" &&
    Array.isArray(pair.diff_fields) &&
    pair.diff_fields.length > 0;

  return (
    <div
      className={`grid grid-cols-[78px_1fr_1fr] border-t border-dashed border-[#f3f4f6] ${rowBg}`}
      data-pair-key={pairKey}
    >
      <div
        className={`${checksBg} flex flex-col items-center gap-[0.3rem] border-r border-dashed border-[#e5e7eb] px-[0.35rem] py-2 text-[0.65rem] font-semibold leading-none`}
      >
        <div className="flex gap-[0.3rem]">
          <RadioPill
            name={radioName}
            side="xlsx"
            checked={effectiveChoice === "xlsx"}
            disabled={!hasXlsx || protectedPair}
            onChange={() => onChoiceChange(pair.pair_uid, "xlsx")}
          />
          <RadioPill
            name={radioName}
            side="db"
            checked={effectiveChoice === "db"}
            disabled={!hasDb || protectedPair}
            onChange={() => onChoiceChange(pair.pair_uid, "db")}
            lockHint={protectedPair}
          />
        </div>
        {showDivergentMarker && (
          <span className="text-[0.7rem] text-[#dc2626] text-center break-words">
            ⚠ {pair.diff_fields.join(", ")}
          </span>
        )}
      </div>
      <StepCell
        step={pair.xlsx}
        source="xlsx"
        className={xlsxCellClass(pair)}
        isChild={isChild}
      />
      <StepCell
        step={pair.db}
        source="db"
        className={dbCellClass(pair)}
        isChild={isChild}
      />
    </div>
  );
}

function RadioPill({
  name,
  side,
  checked,
  disabled,
  onChange,
  lockHint = false,
}: {
  name: string;
  side: PairChoice;
  checked: boolean;
  disabled: boolean;
  onChange: () => void;
  lockHint?: boolean;
}) {
  const labelText = side === "xlsx" ? "XLSX" : "BDD";
  // accent-color via inline style : Tailwind ne génère pas accent-[color]
  // de façon fiable v4, on force via style pour matcher #16a34a / #2563eb.
  const accent = side === "xlsx" ? "#16a34a" : "#2563eb";
  const titleText =
    side === "xlsx"
      ? "Garder version XLSX"
      : lockHint
        ? "Verrouillé par migration_id"
        : "Garder version BDD";
  return (
    <label
      className={`flex flex-col items-center gap-[0.1rem] leading-none font-semibold text-[0.65rem] ${
        disabled ? "opacity-25 cursor-not-allowed" : "cursor-pointer"
      }`}
      title={titleText}
    >
      <input
        type="radio"
        name={name}
        checked={checked}
        disabled={disabled}
        onChange={onChange}
        className="h-[14px] w-[14px]"
        style={{ accentColor: accent }}
      />
      <span>
        {labelText}
        {lockHint && side === "db" && (
          <span className="ml-[0.15rem] text-[0.85rem] align-middle">🔒</span>
        )}
      </span>
    </label>
  );
}

// Labels traduits des catégories pour les badges/stats. Utilisé par
// apply-flow pour la stats line (clé brute + valeur).
export const CATEGORY_LABEL: Record<PairCategory, string> = {
  common: "Identique",
  common_divergent: "Modifié",
  rename: "Renommé",
  xlsx_only: "Ajout XLSX",
  db_only_volontaire: "Volontaire (BDD)",
  db_only_orphan: "Orphelin (BDD)",
};
