"use client";

/**
 * 2026-11-11 — Template → Template Content (main CRM).
 * The sidebar already linked here (/templates/templates_content) but the page did not exist.
 * Edits the rows of certification_db.template_contents — the time-plan rows printed in the Audit Plan
 * documents of scheme.qrs.ae (and the main CRM job documents). Changes apply to documents generated
 * AFTER saving; documents already downloaded are not changed.
 */
import React, { useEffect, useMemo, useState } from "react";
import toast from "react-hot-toast";
import { AppToaster } from "@/components/AppToaster";
import {
  createContent,
  deleteContent,
  listAllContents,
  listContents,
  listTemplatesLite,
  updateContent,
  type TemplateContentRow,
  type TemplateLite,
} from "@/lib/api/template-content.api";

const C = { brand: "#760E9E", border: "#e6e8ee", muted: "#667085", text: "#101828" };

type Draft = { startTime: string; endTime: string; content: string; functional_area: string; title: string };
const EMPTY: Draft = { startTime: "", endTime: "", content: "", functional_area: "", title: "" };
const hhmm = (t?: string | null) => (t ? String(t).slice(0, 5) : "");
const stageOf = (t: TemplateLite) => t.stageName ?? t.stage_name ?? "";
const activeOf = (t: TemplateLite) => !(t.isActive === false || t.isActive === 0 || t.is_active === 0 || t.is_active === false);

export default function TemplateContentPage() {
  const [templates, setTemplates] = useState<TemplateLite[]>([]);
  const [stage, setStage] = useState<string>("");
  const [tq, setTq] = useState("");
  const [showInactive, setShowInactive] = useState(false);
  const [onlyWithContent, setOnlyWithContent] = useState(true); // 2026-11-11: like scheme.qrs.ae — templates that have content
  const [tplId, setTplId] = useState<number | null>(null);
  const [rows, setRows] = useState<TemplateContentRow[]>([]);
  const [counts, setCounts] = useState<Record<number, number>>({});
  const [loading, setLoading] = useState(false);
  const [editId, setEditId] = useState<number | "new" | null>(null);
  const [draft, setDraft] = useState<Draft>(EMPTY);
  const [busy, setBusy] = useState(false);

  // 2026-11-11 — row counts for every template from one call (same data as scheme.qrs.ae's Template Content page)
  const loadCounts = () =>
    listAllContents()
      .then((all) => {
        const c: Record<number, number> = {};
        for (const r of all) c[r.template_id] = (c[r.template_id] ?? 0) + 1;
        setCounts(c);
      })
      .catch(() => undefined);
  useEffect(() => {
    loadCounts();
  }, []);

  useEffect(() => {
    listTemplatesLite()
      .then((t) => setTemplates(t.sort((a, b) => stageOf(a).localeCompare(stageOf(b)) || a.name.localeCompare(b.name))))
      .catch((e) => toast.error(e?.message || "Could not load templates"));
  }, []);

  const shownTemplates = useMemo(() => {
    const s = tq.trim().toLowerCase();
    return templates.filter(
      (t) =>
        (showInactive || activeOf(t)) &&
        (!onlyWithContent || (counts[t.id] ?? 0) > 0) &&
        (!stage || stageOf(t) === stage) &&
        (!s || t.name.toLowerCase().includes(s)),
    );
  }, [templates, stage, tq, showInactive, onlyWithContent, counts]);
  const stages = useMemo(() => [...new Set(templates.map(stageOf).filter(Boolean))], [templates]);
  const tpl = templates.find((t) => t.id === tplId) || null;

  const load = (id: number) => {
    setLoading(true);
    listContents(id)
      .then((r) => {
        const list = Array.isArray(r) ? r : [];
        setRows(list);
        setCounts((c) => ({ ...c, [id]: list.length }));
      })
      .catch((e) => toast.error(e?.message || "Could not load content"))
      .finally(() => setLoading(false));
  };
  useEffect(() => {
    if (tplId) load(tplId);
    setEditId(null);
  }, [tplId]);

  const startEdit = (r: TemplateContentRow) => {
    setEditId(r.id);
    setDraft({
      startTime: hhmm(r.startTime),
      endTime: hhmm(r.endTime),
      content: r.content ?? "",
      functional_area: r.functional_area ?? "",
      title: r.title ?? "",
    });
  };
  const startNew = () => {
    const last = rows[rows.length - 1];
    setEditId("new");
    setDraft({ ...EMPTY, startTime: hhmm(last?.endTime) });
  };

  const save = async () => {
    if (!tplId) return;
    if (!draft.content.trim()) return toast.error("Content is required");
    if (draft.startTime && draft.endTime && draft.endTime <= draft.startTime) return toast.error("End time must be after start time");
    const body = {
      startTime: draft.startTime ? `${draft.startTime}:00` : undefined,
      endTime: draft.endTime ? `${draft.endTime}:00` : undefined,
      content: draft.content,
      functional_area: draft.functional_area || undefined,
      title: draft.title || undefined,
    };
    setBusy(true);
    try {
      if (editId === "new") await createContent({ template_id: tplId, ...body });
      else if (typeof editId === "number") await updateContent(editId, body);
      toast.success("Saved — new documents will use this content");
      setEditId(null);
      load(tplId);
      loadCounts();
    } catch (e: any) {
      toast.error(e?.message || "Save failed");
    } finally {
      setBusy(false);
    }
  };

  const remove = async (r: TemplateContentRow) => {
    if (!window.confirm(`Delete this row${r.startTime ? ` (${hhmm(r.startTime)}–${hhmm(r.endTime)})` : ""}?\n\nIt will no longer print on new documents of "${tpl?.name}".`)) return;
    setBusy(true);
    try {
      await deleteContent(r.id);
      toast.success("Row deleted");
      if (tplId) load(tplId);
      loadCounts();
    } catch (e: any) {
      toast.error(e?.message || "Delete failed");
    } finally {
      setBusy(false);
    }
  };

  const editor = (
    <tr style={{ background: "#faf5ff" }}>
      <td style={td}>
        <input type="time" value={draft.startTime} onChange={(e) => setDraft({ ...draft, startTime: e.target.value })} style={{ ...inp, width: 110 }} />
        <div style={{ height: 4 }} />
        <input type="time" value={draft.endTime} onChange={(e) => setDraft({ ...draft, endTime: e.target.value })} style={{ ...inp, width: 110 }} />
      </td>
      <td style={td}>
        <textarea
          value={draft.content}
          onChange={(e) => setDraft({ ...draft, content: e.target.value })}
          rows={Math.min(14, Math.max(4, draft.content.split("\n").length + 1))}
          placeholder="One item per line — e.g. Opening meeting and interview with top management"
          style={{ ...inp, width: "100%", height: "auto", padding: 8, fontFamily: "inherit", lineHeight: 1.45 }}
          autoFocus
        />
        <input value={draft.title} onChange={(e) => setDraft({ ...draft, title: e.target.value })} placeholder="Title (optional)" style={{ ...inp, width: "100%", marginTop: 6 }} />
      </td>
      <td style={td}>
        <input value={draft.functional_area} onChange={(e) => setDraft({ ...draft, functional_area: e.target.value })} placeholder="e.g. Lead auditor / Production" style={{ ...inp, width: "100%" }} />
      </td>
      <td style={{ ...td, whiteSpace: "nowrap" }}>
        <button type="button" disabled={busy} onClick={save} style={btnPrimary}>
          {busy ? "Saving…" : "Save"}
        </button>{" "}
        <button type="button" disabled={busy} onClick={() => setEditId(null)} style={btnGhost}>
          Cancel
        </button>
      </td>
    </tr>
  );

  return (
    <div style={{ padding: 16 }}>
      <AppToaster />
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 12, flexWrap: "wrap", marginBottom: 14 }}>
        <div>
          <h1 style={{ margin: 0, fontSize: 22, color: C.text }}>Template Content</h1>
          <p style={{ margin: "4px 0 0", fontSize: 13, color: C.muted, maxWidth: 760 }}>
            The time-plan rows printed in the Audit Plan documents (scheme.qrs.ae and the CRM job documents). Changes apply to every document generated after you save.
          </p>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "minmax(260px, 340px) 1fr", gap: 16, alignItems: "start" }}>
        {/* template list */}
        <div style={{ border: `1px solid ${C.border}`, borderRadius: 12, background: "#fff", overflow: "hidden" }}>
          <div style={{ padding: 10, borderBottom: `1px solid ${C.border}`, display: "grid", gap: 8 }}>
            <input value={tq} onChange={(e) => setTq(e.target.value)} placeholder="Search template…" style={{ ...inp, width: "100%" }} />
            <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
              {["", ...stages].map((s) => (
                <button key={s || "all"} type="button" onClick={() => setStage(s)} style={{ ...chip, background: stage === s ? C.brand : "#fff", color: stage === s ? "#fff" : "#344054", borderColor: stage === s ? C.brand : "#d0d5dd" }}>
                  {s || "All"}
                </button>
              ))}
              <label style={{ fontSize: 12, color: C.muted, display: "flex", alignItems: "center", gap: 4, marginLeft: "auto" }}>
                <input type="checkbox" checked={showInactive} onChange={(e) => setShowInactive(e.target.checked)} /> inactive
              </label>
            </div>
            <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
              <label style={{ fontSize: 12, color: C.muted, display: "flex", alignItems: "center", gap: 4 }}>
                <input type="checkbox" checked={onlyWithContent} onChange={(e) => setOnlyWithContent(e.target.checked)} /> only templates with content
                {" "}({Object.keys(counts).length})
              </label>
            </div>
          </div>
          <div style={{ maxHeight: "68vh", overflowY: "auto" }}>
            {shownTemplates.length === 0 ? (
              <div style={{ padding: 16, fontSize: 13, color: C.muted }}>No templates.</div>
            ) : (
              shownTemplates.map((t) => {
                const on = t.id === tplId;
                return (
                  <button
                    key={t.id}
                    type="button"
                    onClick={() => setTplId(t.id)}
                    style={{ display: "block", width: "100%", textAlign: "left", padding: "9px 12px", border: "none", borderBottom: "1px solid #f2f4f7", cursor: "pointer", background: on ? "#f4ebf8" : "#fff", borderLeft: `3px solid ${on ? C.brand : "transparent"}` }}
                  >
                    <div style={{ fontSize: 13, fontWeight: on ? 700 : 600, color: C.text }}>{t.name}</div>
                    <div style={{ fontSize: 11.5, color: C.muted }}>
                      {stageOf(t) || "—"} · #{t.id}
                      {!activeOf(t) && " · inactive"}
                      {` · ${counts[t.id] ?? 0} row${(counts[t.id] ?? 0) === 1 ? "" : "s"}`}
                    </div>
                  </button>
                );
              })
            )}
          </div>
        </div>

        {/* content editor */}
        <div style={{ border: `1px solid ${C.border}`, borderRadius: 12, background: "#fff", minHeight: 300 }}>
          {!tpl ? (
            <div style={{ padding: 40, textAlign: "center", color: C.muted, fontSize: 14 }}>← Choose a template to see and edit its content.</div>
          ) : (
            <>
              <div style={{ padding: "12px 14px", borderBottom: `1px solid ${C.border}`, display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 700, fontSize: 15, color: C.text }}>{tpl.name}</div>
                  <div style={{ fontSize: 12, color: C.muted }}>
                    {stageOf(tpl)} · {rows.length} row{rows.length === 1 ? "" : "s"} · rows print in time order
                  </div>
                </div>
                <button type="button" disabled={busy || editId !== null} onClick={startNew} style={{ ...btnPrimary, opacity: editId !== null ? 0.5 : 1 }}>
                  + Add row
                </button>
              </div>
              <div style={{ overflowX: "auto" }}>
                <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
                  <thead>
                    <tr style={{ background: "#f9fafb" }}>
                      <th style={{ ...th, width: 130 }}>Time</th>
                      <th style={th}>Content</th>
                      <th style={{ ...th, width: 200 }}>Functional area / auditor</th>
                      <th style={{ ...th, width: 150 }}></th>
                    </tr>
                  </thead>
                  <tbody>
                    {loading ? (
                      <tr>
                        <td colSpan={4} style={{ padding: 30, textAlign: "center", color: C.muted }}>Loading…</td>
                      </tr>
                    ) : (
                      <>
                        {rows.length === 0 && editId !== "new" && (
                          <tr>
                            <td colSpan={4} style={{ padding: 30, textAlign: "center", color: C.muted }}>
                              This template has no content rows. Use “+ Add row”.
                            </td>
                          </tr>
                        )}
                        {rows.map((r) =>
                          editId === r.id ? (
                            <React.Fragment key={r.id}>{editor}</React.Fragment>
                          ) : (
                            <tr key={r.id} style={{ borderTop: "1px solid #f2f4f7" }}>
                              <td style={{ ...td, whiteSpace: "nowrap", fontWeight: 600 }}>
                                {r.startTime ? `${hhmm(r.startTime)} – ${hhmm(r.endTime)}` : <span style={{ color: "#98a2b3" }}>no time</span>}
                              </td>
                              <td style={td}>
                                {r.title && <div style={{ fontWeight: 700, marginBottom: 2 }}>{r.title}</div>}
                                <div style={{ whiteSpace: "pre-wrap", lineHeight: 1.45 }}>{r.content}</div>
                              </td>
                              <td style={td}>{r.functional_area || <span style={{ color: "#98a2b3" }}>—</span>}</td>
                              <td style={{ ...td, whiteSpace: "nowrap" }}>
                                <button type="button" disabled={busy || editId !== null} onClick={() => startEdit(r)} style={btnGhost}>
                                  Edit
                                </button>{" "}
                                <button type="button" disabled={busy || editId !== null} onClick={() => remove(r)} style={{ ...btnGhost, color: "#b42318", borderColor: "#fecdca" }}>
                                  Delete
                                </button>
                              </td>
                            </tr>
                          ),
                        )}
                        {editId === "new" && editor}
                      </>
                    )}
                  </tbody>
                </table>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

const inp: React.CSSProperties = { height: 34, padding: "0 10px", border: "1px solid #d0d5dd", borderRadius: 8, fontSize: 13, background: "#fff", color: "#101828", boxSizing: "border-box" };
const th: React.CSSProperties = { textAlign: "left", padding: "9px 12px", fontSize: 11, fontWeight: 700, color: "#475467", textTransform: "uppercase", letterSpacing: ".03em", borderBottom: "1px solid #e6e8ee" };
const td: React.CSSProperties = { padding: "9px 12px", verticalAlign: "top", color: "#344054" };
const chip: React.CSSProperties = { height: 26, padding: "0 10px", borderRadius: 999, fontSize: 12, fontWeight: 600, cursor: "pointer", border: "1px solid #d0d5dd" };
const btnPrimary: React.CSSProperties = { height: 32, padding: "0 12px", border: "none", borderRadius: 8, background: "#760E9E", color: "#fff", fontWeight: 700, fontSize: 12.5, cursor: "pointer" };
const btnGhost: React.CSSProperties = { height: 32, padding: "0 10px", border: "1px solid #d0d5dd", borderRadius: 8, background: "#fff", color: "#344054", fontWeight: 600, fontSize: 12.5, cursor: "pointer" };
