import React, { useEffect, useMemo, useState } from "react";
import { DashboardTemplatePage } from "./DashboardTemplatePage";
import { useLogoManifest } from "./useLogoManifest";
import { LogoTemplateItem } from "./logo-manifest";

type Row = {
  id: string;
  name: string;
  svgUrl: string;
  previewUrl?: string;
  okTokens: boolean;
  okColors: boolean;
  okPreview: boolean;
  okSVG: boolean;
  notes: string[];
};

export default function AdminValidateManifest() {
  const state = useLogoManifest("/site/data/manifest.logo.json");
  const [rows, setRows] = useState<Row[]>([]);
  const [running, setRunning] = useState(false);

  const tokensRequired = ["{Brand_Name}", "{Tagline}", "{Est_Year}"];
  const cssVarsRequired = ["--primary", "--secondary", "--accent"];

  useEffect(() => {
    if (state.status !== "ready") return;
    // Auto-run on load; you can remove this if you want manual
    validateAll(state.items);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [state.status]);

  const validateAll = async (items: LogoTemplateItem[]) => {
    setRunning(true);
    const out: Row[] = [];
    for (const it of items) {
      const notes: string[] = [];
      let svgText = "";
      let okSVG = false;
      try {
        const res = await fetch(it.svgUrl, { cache: "no-cache" });
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        svgText = await res.text();
        okSVG = /^\s*<svg[\s\S]*<\/svg>\s*$/i.test(svgText);
        if (!okSVG) notes.push("SVG: not a valid <svg>…</svg> document");
      } catch (e: any) {
        notes.push(`SVG fetch failed: ${e?.message || "unknown error"}`);
      }

      const okTokens = tokensRequired.every(t => svgText.includes(t));
      if (!okTokens) notes.push("Missing one or more tokens {Brand_Name}/{Tagline}/{Est_Year}");

      const okColors = cssVarsRequired.every(v => svgText.includes(v));
      if (!okColors) notes.push("Missing one or more CSS vars --primary/--secondary/--accent");

      const okPreview = !!it.previewUrl;
      if (!okPreview) notes.push("No previewUrl set");

      out.push({
        id: it.id,
        name: it.name,
        svgUrl: it.svgUrl,
        previewUrl: it.previewUrl,
        okTokens,
        okColors,
        okPreview,
        okSVG,
        notes
      });
    }
    setRows(out);
    setRunning(false);
  };

  const summary = useMemo(() => {
    const total = rows.length;
    const pass = rows.filter(r => r.okTokens && r.okColors && r.okSVG && r.okPreview).length;
    return { total, pass, fail: total - pass };
  }, [rows]);

  const downloadCSV = () => {
    const header = [
      "id","name","svgUrl","previewUrl","okTokens","okColors","okPreview","okSVG","notes"
    ].join(",");
    const lines = rows.map(r =>
      [
        csv(r.id),
        csv(r.name),
        csv(r.svgUrl),
        csv(r.previewUrl || ""),
        r.okTokens,
        r.okColors,
        r.okPreview,
        r.okSVG,
        csv(r.notes.join(" | "))
      ].join(",")
    );
    const blob = new Blob([header + "\n" + lines.join("\n")], { type: "text/csv;charset=utf-8" });
    const url = URL.createObjectURL(blob);
    triggerDownload(url, "logo-manifest-validation.csv");
    URL.revokeObjectURL(url);
  };

  return (
    <DashboardTemplatePage title="Validate Logo Manifest">
      {state.status !== "ready" ? (
        <div className="text-sm text-gray-500">
          {state.status === "error" ? `Error: ${state.error}` : "Loading manifest…"}
        </div>
      ) : (
        <>
          <div className="mb-4 flex items-center gap-3">
            <button
              className="rounded-xl px-4 py-2 border hover:bg-gray-50"
              onClick={() => validateAll(state.items)}
              disabled={running}
            >
              {running ? "Validating…" : "Re-Run Validation"}
            </button>
            <button
              className="rounded-xl px-4 py-2 border hover:bg-gray-50"
              onClick={downloadCSV}
              disabled={!rows.length}
            >
              Download CSV
            </button>
            <div className="text-sm text-gray-600">
              {rows.length ? `Pass: ${summary.pass}/${summary.total} | Fail: ${summary.fail}` : null}
            </div>
          </div>

          <div className="overflow-auto rounded-2xl border">
            <table className="min-w-full text-sm">
              <thead className="bg-gray-50">
                <tr>
                  <Th>ID</Th>
                  <Th>Name</Th>
                  <Th>Tokens</Th>
                  <Th>Colors</Th>
                  <Th>Preview</Th>
                  <Th>SVG</Th>
                  <Th>Notes</Th>
                </tr>
              </thead>
              <tbody>
                {rows.map((r) => (
                  <tr key={r.id} className="border-t">
                    <Td mono>{r.id}</Td>
                    <Td>{r.name}</Td>
                    <Td>{okBadge(r.okTokens)}</Td>
                    <Td>{okBadge(r.okColors)}</Td>
                    <Td>{okBadge(r.okPreview)}</Td>
                    <Td>{okBadge(r.okSVG)}</Td>
                    <Td className="max-w-[520px]">{r.notes.join(" | ") || "—"}</Td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </>
      )}
    </DashboardTemplatePage>
  );
}

function Th({ children }: { children: React.ReactNode }) {
  return <th className="text-left px-4 py-3 font-medium text-gray-700">{children}</th>;
}
function Td({ children, mono }: { children: React.ReactNode; mono?: boolean }) {
  return <td className={`px-4 py-3 align-top ${mono ? "font-mono text-xs" : ""}`}>{children}</td>;
}
function okBadge(ok: boolean) {
  return (
    <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs ${ok ? "bg-green-100 text-green-700" : "bg-rose-100 text-rose-700"}`}>
      {ok ? "OK" : "Issue"}
    </span>
  );
}
function csv(s: string) {
  const v = s.replace(/"/g, '""');
  return `"${v}"`;
}
function triggerDownload(url: string, filename: string) {
  const a = document.createElement("a");
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  a.remove();
}
