import React, { useMemo, useState } from "react";
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 function ValidateManifestButton() {
  const state = useLogoManifest("/site/data/manifest.logo.json");
  const [open, setOpen] = useState(false);
  const [running, setRunning] = useState(false);
  const [rows, setRows] = useState<Row[]>([]);

  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 runValidation = async () => {
    if (state.status !== "ready") return;
    setOpen(true);
    setRunning(true);
    const tokensRequired = ["{Brand_Name}", "{Tagline}", "{Est_Year}"];
    const cssVarsRequired = ["--primary", "--secondary", "--accent"];
    const out: Row[] = [];

    for (const it of state.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 disabled = state.status !== "ready" || running;

  return (
    <>
      <button
        className="rounded-xl px-4 py-2 border hover:bg-gray-50"
        disabled={disabled}
        onClick={runValidation}
        title="Scan all SVGs and flag issues"
      >
        {running ? "Validating…" : "Validate Manifest"}
      </button>

      {!open ? null : (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4" onClick={()=>setOpen(false)}>
          <div className="w-full max-w-5xl rounded-2xl bg-white shadow-xl overflow-hidden" onClick={(e)=>e.stopPropagation()}>
            <div className="flex items-center justify-between px-6 py-4 border-b">
              <div className="text-base font-semibold">Manifest Validation</div>
              <button className="text-sm text-gray-500 hover:text-gray-700" onClick={()=>setOpen(false)}>Close</button>
            </div>

            <div className="px-6 py-4 space-y-3">
              {state.status !== "ready" ? (
                <div className="text-sm text-gray-500">
                  {state.status === "error" ? `Error: ${state.error}` : "Loading manifest…"}
                </div>
              ) : (
                <>
                  <div className="text-sm text-gray-600">
                    {rows.length
                      ? <>Pass: <b>{summary.pass}</b> / {summary.total} &nbsp;|&nbsp; Fail: <b>{summary.fail}</b></>
                      : "Click Validate Manifest to scan all entries."}
                  </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>
                </>
              )}
            </div>
          </div>
        </div>
      )}
    </>
  );
}

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>
  );
}
