/* ==================================================================
   Admin → Classes & Subjects
   ------------------------------------------------------------------
   Manage the class_sections and subjects rows that drive every test
   creation picker, every roster import, and the teacher-assignment
   matrix. Earlier they only grew (auto-inserted by test creation /
   roster import) and any typo ("hi" as a subject) lingered forever.
   This screen lets the admin rename or delete them, with delete
   blocked when something still references the row.
   ================================================================== */

const { Icon: TxIcon } = window.AppUI;

const TaxonomyScreen = () => {
  return (
    <div className="cx-page" style={{ maxWidth: 1100 }}>
      <window.AppUI.PageHeader
        eyebrow="Admin · catalog"
        title="Classes & Subjects"
        meta={["Edit the catalog used by every test-creation picker and the teacher-assignment matrix. Delete is blocked when an entry is still referenced by tests, students, or concepts."]}
      />

      <div className="cx-catalog-split even" style={{ gap: 20 }}>
        <ClassesPanel/>
        <SubjectsPanel/>
      </div>
    </div>
  );
};

/* --------------------- shared bits --------------------- */

const useList = (path) => {
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState(null);
  const refresh = React.useCallback(async () => {
    setLoading(true); setErr(null);
    try { setItems(await window.AppApi.get(path)); }
    catch (e) { setErr(String(e.message || e)); }
    finally { setLoading(false); }
  }, [path]);
  React.useEffect(() => { refresh(); }, [refresh]);
  return { items, loading, err, refresh };
};

const ErrBanner = ({ err, onClear }) => err ? (
  <div className="ui-alert red" style={{
    margin: "10px 16px", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 10,
  }}>
    <span>{err}</span>
    {onClear && <button className="btn ghost xs icon-only" onClick={onClear} aria-label="Dismiss" title="Dismiss"><TxIcon name="x" size={13}/></button>}
  </div>
) : null;

/* --------------------- classes panel --------------------- */

const ClassesPanel = () => {
  const { items, loading, err, refresh } = useList("/admin/class-sections");
  const [actionErr, setActionErr] = React.useState(null);
  const [adding, setAdding] = React.useState(false);
  const [editingId, setEditingId] = React.useState(null);

  const create = async (draft) => {
    setActionErr(null);
    try { await window.AppApi.post("/admin/class-sections", draft); setAdding(false); await refresh(); }
    catch (e) { setActionErr(String(e.message || e)); }
  };
  const update = async (id, draft) => {
    setActionErr(null);
    try { await window.AppApi.patch(`/admin/class-sections/${id}`, draft); setEditingId(null); await refresh(); }
    catch (e) { setActionErr(String(e.message || e)); }
  };
  const remove = async (row) => {
    if (!window.confirm(`Delete class "${row.label}" (${row.academic_year})?`)) return;
    setActionErr(null);
    try { await window.AppApi.del(`/admin/class-sections/${row.id}`); await refresh(); }
    catch (e) { setActionErr(String(e.message || e)); }
  };

  return (
    <div className="cx-card flush">
      <div className="cx-card-head" style={{ padding: "18px 20px", margin: 0, borderBottom: "1px solid var(--line)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span className="cx-card-title">Classes</span>
          <span className="ui-tab-count">{items.length}</span>
        </div>
        <button className="btn sm primary" onClick={() => setAdding(true)} disabled={adding}>
          <TxIcon name="plus" size={14}/>Add class
        </button>
      </div>
      <div>
        <ErrBanner err={actionErr} onClear={() => setActionErr(null)}/>
        {adding && (
          <ClassEditor onCancel={() => setAdding(false)} onSave={create}/>
        )}
        {loading && <div style={{ padding: "16px 20px", color: "var(--ink-3)", fontSize: 13 }}>Loading…</div>}
        <ErrBanner err={err}/>
        {!loading && items.length === 0 && !adding && (
          <window.AppUI.EmptyState compact icon="cap" title="No classes yet"/>
        )}
        {items.map(row =>
          editingId === row.id
            ? <ClassEditor key={row.id} initial={row} onCancel={() => setEditingId(null)} onSave={(d) => update(row.id, d)}/>
            : <ClassRow key={row.id} row={row} onEdit={() => setEditingId(row.id)} onDelete={() => remove(row)}/>
        )}
      </div>
    </div>
  );
};

const ClassRow = ({ row, onEdit, onDelete }) => {
  const safeToDelete = row.test_count === 0 && row.student_count === 0;
  return (
    <div className="ui-row" style={{ padding: "12px 20px", gap: 6 }}>
      <div className="ui-row-main">
        <div className="ui-row-title">
          {row.label} <span className="muted" style={{ fontSize: 12, marginLeft: 4, fontWeight: 400 }}>{row.academic_year}</span>
        </div>
        <div className="ui-row-sub tabular">
          {row.test_count} test{row.test_count === 1 ? "" : "s"} · {row.student_count} student{row.student_count === 1 ? "" : "s"} · {row.assignment_count} scope{row.assignment_count === 1 ? "" : "s"}
        </div>
      </div>
      <window.AppUI.IconButton icon="edit" label="Rename" size={15} className="sm" onClick={onEdit}/>
      <window.AppUI.IconButton icon="trash" label={safeToDelete ? "Delete" : "In use — cannot delete"} size={15}
        className="sm" onClick={onDelete} disabled={!safeToDelete}
        style={{ color: safeToDelete ? "var(--red)" : "var(--ink-3)" }}/>
    </div>
  );
};

const ClassEditor = ({ initial, onCancel, onSave }) => {
  const [classLevel, setClassLevel] = React.useState(initial?.class_level || "");
  const [section, setSection] = React.useState(initial?.section || "");
  const [academicYear, setAcademicYear] = React.useState(initial?.academic_year || "");
  const [busy, setBusy] = React.useState(false);
  const submit = async () => {
    if (!classLevel.trim()) return;
    setBusy(true);
    try {
      await onSave({
        class_level: classLevel.trim(),
        section: section.trim() || null,
        ...(academicYear.trim() ? { academic_year: academicYear.trim() } : {}),
      });
    } finally { setBusy(false); }
  };
  return (
    <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--line)", background: "var(--surface-hover)" }}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(120px, 1fr))", gap: 10 }}>
        <div className="field" style={{ margin: 0 }}>
          <label className="label">Class level *</label>
          <input className="input" autoFocus value={classLevel} onChange={e => setClassLevel(e.target.value)}
            placeholder="e.g. X" style={{ width: "100%" }}/>
        </div>
        <div className="field" style={{ margin: 0 }}>
          <label className="label">Section</label>
          <input className="input" value={section} onChange={e => setSection(e.target.value)}
            placeholder="e.g. A" style={{ width: "100%" }}/>
        </div>
        <div className="field" style={{ margin: 0 }}>
          <label className="label">Academic year</label>
          <input className="input" value={academicYear} onChange={e => setAcademicYear(e.target.value)}
            placeholder="defaults to school year" style={{ width: "100%" }}/>
        </div>
      </div>
      <div style={{ display: "flex", justifyContent: "flex-end", gap: 6, marginTop: 12 }}>
        <button className="btn sm" onClick={onCancel} disabled={busy}>Cancel</button>
        <button className="btn sm primary" onClick={submit} disabled={busy || !classLevel.trim()}>
          {busy ? "Saving…" : initial ? "Save" : "Add class"}
        </button>
      </div>
    </div>
  );
};

/* --------------------- subjects panel --------------------- */

const SubjectsPanel = () => {
  const { items, loading, err, refresh } = useList("/admin/subjects");
  const [actionErr, setActionErr] = React.useState(null);
  const [adding, setAdding] = React.useState(false);
  const [editingId, setEditingId] = React.useState(null);

  const create = async (draft) => {
    setActionErr(null);
    try { await window.AppApi.post("/admin/subjects", draft); setAdding(false); await refresh(); }
    catch (e) { setActionErr(String(e.message || e)); }
  };
  const update = async (id, draft) => {
    setActionErr(null);
    try { await window.AppApi.patch(`/admin/subjects/${id}`, draft); setEditingId(null); await refresh(); }
    catch (e) { setActionErr(String(e.message || e)); }
  };
  const remove = async (row) => {
    if (!window.confirm(`Delete subject "${row.name}"?`)) return;
    setActionErr(null);
    try { await window.AppApi.del(`/admin/subjects/${row.id}`); await refresh(); }
    catch (e) { setActionErr(String(e.message || e)); }
  };

  return (
    <div className="cx-card flush">
      <div className="cx-card-head" style={{ padding: "18px 20px", margin: 0, borderBottom: "1px solid var(--line)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span className="cx-card-title">Subjects</span>
          <span className="ui-tab-count">{items.length}</span>
        </div>
        <button className="btn sm primary" onClick={() => setAdding(true)} disabled={adding}>
          <TxIcon name="plus" size={14}/>Add subject
        </button>
      </div>
      <div>
        <ErrBanner err={actionErr} onClear={() => setActionErr(null)}/>
        {adding && (
          <SubjectEditor onCancel={() => setAdding(false)} onSave={create}/>
        )}
        {loading && <div style={{ padding: "16px 20px", color: "var(--ink-3)", fontSize: 13 }}>Loading…</div>}
        <ErrBanner err={err}/>
        {!loading && items.length === 0 && !adding && (
          <window.AppUI.EmptyState compact icon="book" title="No subjects yet"/>
        )}
        {items.map(row =>
          editingId === row.id
            ? <SubjectEditor key={row.id} initial={row} onCancel={() => setEditingId(null)} onSave={(d) => update(row.id, d)}/>
            : <SubjectRow key={row.id} row={row} onEdit={() => setEditingId(row.id)} onDelete={() => remove(row)}/>
        )}
      </div>
    </div>
  );
};

const SubjectRow = ({ row, onEdit, onDelete }) => {
  const safeToDelete = row.test_count === 0 && row.concept_count === 0;
  return (
    <div className="ui-row" style={{ padding: "12px 20px", gap: 6 }}>
      <div className="ui-row-main">
        <div className="ui-row-title">
          {row.name}
          {row.short_code && <span className="ui-id" style={{ marginLeft: 8 }}>{row.short_code}</span>}
        </div>
        <div className="ui-row-sub tabular">
          {row.test_count} test{row.test_count === 1 ? "" : "s"} · {row.assignment_count} scope{row.assignment_count === 1 ? "" : "s"} · {row.concept_count} concept{row.concept_count === 1 ? "" : "s"}
        </div>
      </div>
      <window.AppUI.IconButton icon="edit" label="Rename" size={15} className="sm" onClick={onEdit}/>
      <window.AppUI.IconButton icon="trash" label={safeToDelete ? "Delete" : "In use — cannot delete"} size={15}
        className="sm" onClick={onDelete} disabled={!safeToDelete}
        style={{ color: safeToDelete ? "var(--red)" : "var(--ink-3)" }}/>
    </div>
  );
};

const SubjectEditor = ({ initial, onCancel, onSave }) => {
  const [name, setName] = React.useState(initial?.name || "");
  const [shortCode, setShortCode] = React.useState(initial?.short_code || "");
  const [busy, setBusy] = React.useState(false);
  const submit = async () => {
    if (!name.trim()) return;
    setBusy(true);
    try {
      await onSave({ name: name.trim(), short_code: shortCode.trim() || null });
    } finally { setBusy(false); }
  };
  return (
    <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--line)", background: "var(--surface-hover)" }}>
      <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 10 }}>
        <div className="field" style={{ margin: 0 }}>
          <label className="label">Name *</label>
          <input className="input" autoFocus value={name} onChange={e => setName(e.target.value)}
            placeholder="e.g. Chemistry" style={{ width: "100%" }}/>
        </div>
        <div className="field" style={{ margin: 0 }}>
          <label className="label">Short code</label>
          <input className="input" value={shortCode} onChange={e => setShortCode(e.target.value)}
            placeholder="e.g. CHEM" style={{ width: "100%" }}/>
        </div>
      </div>
      <div style={{ display: "flex", justifyContent: "flex-end", gap: 6, marginTop: 12 }}>
        <button className="btn sm" onClick={onCancel} disabled={busy}>Cancel</button>
        <button className="btn sm primary" onClick={submit} disabled={busy || !name.trim()}>
          {busy ? "Saving…" : initial ? "Save" : "Add subject"}
        </button>
      </div>
    </div>
  );
};

window.TaxonomyScreen = TaxonomyScreen;
