import React, { useEffect, useMemo, useState } from "react";
import { DashboardTemplatePage } from "./DashboardTemplatePage";
import { useBPManifest } from "./useBPManifest";
import { COLORS } from "./ui-tokens";

type Row = {
  id: string; name: string;
  preview: boolean; docx: boolean; hasSections: boolean; notes: string[];
};

export default function AdminValidateBPManifest() {
  const state = useBPManifest("/site/data/manifest.bp.json");
  const [rows, setRows] = useState<Row[]>([]);

  useEffect(() => {
    if (state.status !== "ready") return;
    (async () => {
      const out: Row[] = [];
      for (const it of state.items) {
        const notes: string[] = [];
        const preview = await exists(it.previewUrl);
        if (!preview) notes.push("Missing preview");
        const docx = await exists(it.docxUrl);
        if (!docx) notes.push("Missing DOCX");
        const hasSections = !!(it.sections?.length);
        if (!hasSections) notes.push("Consider adding 'sections' list");
        out.push({ id: it.id, name: it.name, preview, docx, hasSections, notes });
      }
      setRows(out);
    })();
  }, [state.status]);

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

  return (
    <DashboardTemplatePage title="Validate Business Plan Manifest">
      {state.status !== "ready" ? (
        <div className="text-sm text-gray-500">
          {state.status === "error" ? `Error: ${state.error}` : "Loading manifest…"}
        </div>
      ) : (
        <>
          <div className="mb-3 text-sm text-gray-600">Pass: <b>{summary.pass}</b> / {summary.total} &nbsp;|&nbsp; Fail: <b>{summary.fail}</b></div>
          <div className="overflow-auto rounded-2xl border bg-white">
            <table className="min-w-full text-sm">
              <thead className="bg-gray-50">
                <tr>
                  <Th>ID</Th><Th>Name</Th><Th>Preview</Th><Th>DOCX</Th><Th>Sections</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>{ok(r.preview)}</Td>
                    <Td>{ok(r.docx)}</Td>
                    <Td>{ok(r.hasSections)}</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 ok(v: boolean) {
  const bg = v ? "#e6f7ec" : "#fde8e8";
  const fg = v ? "#1d7a3c" : "#a61b1b";
  return <span style={{ backgroundColor: bg, color: fg }} className="inline-flex items-center px-2 py-0.5 rounded-full text-xs">{v ? "OK" : "Issue"}</span>;
}
async function exists(url?: string) {
  if (!url) return false;
  try { const r = await fetch(url, { method: "HEAD", cache: "no-cache" }); return r.ok; }
  catch { return false; }
}
