// AdminModuleManagement.jsx — F4. Module whitelist for facility deployment
// (Tokens & modules nav). Type filters, search, an Add Module form, and per-row
// Delete routed through ConfirmAction. The list is App state so add/delete are live.

const MODULE_TYPES = ["Fee", "Liquidity", "Risk", "Valuation", "Auction", "Oracle", "Compliance"];

const mmInput = { width: "100%", height: 40, padding: "0 var(--space-12)", boxSizing: "border-box", borderRadius: "var(--radius-md)", border: "1px solid var(--border-strong)", background: "var(--surface)", color: "var(--fg)", font: '400 14px "Inter", sans-serif' };
const MMLabel = ({ children }) => <label style={{ display: "block", font: '500 13px/18px "Inter", sans-serif', color: "var(--fg)", marginBottom: "var(--space-8)" }}>{children}</label>;

const AddModuleForm = ({ onAdd, onCancel }) => {
  const [type, setType] = React.useState("Compliance");
  const [name, setName] = React.useState("");
  const [desc, setDesc] = React.useState("");
  const [addr, setAddr] = React.useState("");
  const [chainId, setChainId] = React.useState("11155111");
  const ok = name.trim() && addr.trim();
  return (
    <section className="card" data-annot-note="real action → appends to whitelist">
      <SectionHeader eyebrow="Whitelist" title="Add module" />
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "var(--space-16)", maxWidth: 720 }}>
        <div><MMLabel>Module type</MMLabel>
          <select value={type} onChange={(e) => setType(e.target.value)} style={mmInput}>
            {MODULE_TYPES.map((t) => <option key={t} value={t}>{t}</option>)}
          </select>
        </div>
        <div><MMLabel>Name</MMLabel><input value={name} onChange={(e) => setName(e.target.value)} placeholder="Module name" style={mmInput} /></div>
        <div style={{ gridColumn: "1 / -1" }}><MMLabel>Description</MMLabel><input value={desc} onChange={(e) => setDesc(e.target.value)} placeholder="What this module enforces" style={mmInput} /></div>
        <div><MMLabel>Chain address</MMLabel><input value={addr} onChange={(e) => setAddr(e.target.value)} placeholder="0x…" style={{ ...mmInput, fontFamily: "var(--font-mono)", fontSize: 13 }} /></div>
        <div><MMLabel>Chain ID</MMLabel><input value={chainId} onChange={(e) => setChainId(e.target.value)} style={{ ...mmInput, fontFamily: "var(--font-mono)", fontSize: 13 }} /></div>
      </div>
      <div style={{ display: "flex", gap: "var(--space-8)", marginTop: "var(--space-20)" }}>
        <button type="button" className="btn btn--secondary" onClick={onCancel}>Cancel</button>
        <button type="button" className="btn btn--primary" disabled={!ok} style={{ opacity: ok ? 1 : 0.5 }}
          onClick={() => ok && onAdd({ id: "mod-" + name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "").slice(0, 18), name: name.trim(), type, desc: desc.trim(), addr: addr.trim() || "0x…", chainId: parseInt(chainId, 10) || 11155111, updated: new Date().toISOString().slice(0, 10) })}>
          Add module
        </button>
      </div>
    </section>
  );
};

const AdminModuleManagement = ({ modules, onAddModule, onAction, state, onRetry }) => {
  const [filter, setFilter] = React.useState("all");
  const [q, setQ] = React.useState("");
  const [adding, setAdding] = React.useState(false);
  if (state === "loading") return <PageSkeleton shape="rows" />;
  if (state === "error") return <PageError title="Couldn't load the module whitelist" onRetry={onRetry} />;

  const typeCount = (t) => modules.filter((m) => m.type === t).length;
  const filtered = modules.filter((m) =>
    (filter === "all" || m.type === filter) &&
    (q === "" || [m.name, m.type, m.addr].join(" ").toLowerCase().includes(q.toLowerCase()))
  );

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-24)" }}>
      <PageHeader eyebrow="Tokens & modules" title="Module whitelist" icon="settings"
        lede="Manage whitelisted modules for credit facility deployment. Multiple modules of the same type can exist."
        action={!adding && <button className="btn btn--primary" type="button" onClick={() => setAdding(true)}><Icon name="plus" size={14} stroke={1.8} /> Add module</button>} />

      {adding && <AddModuleForm onCancel={() => setAdding(false)} onAdd={(m) => { onAddModule(m); setAdding(false); }} />}

      <div>
        <SectionHeader eyebrow="Whitelist" title="All modules" count={filtered.length}
          action={<SearchBox placeholder="Search by name, type, or address…" value={q} onChange={setQ} width={280} />} />

        <div style={{ marginBottom: "var(--space-16)" }}>
          <SegmentControl value={filter} onChange={setFilter} options={[
            { value: "all", label: "All", count: modules.length },
            ...MODULE_TYPES.map((t) => ({ value: t, label: t, count: typeCount(t) })),
          ]} />
        </div>

        <section className="card" style={{ padding: 0 }}>
          <div className="adm-scroll">
            <div className="adm-table-head" style={{ display: "grid", gridTemplateColumns: "1.6fr 120px 160px 120px 120px 90px", gap: "var(--space-16)", padding: "var(--space-12) var(--space-20)", background: "var(--bg-alt)", borderBottom: "1px solid var(--border)" }}>
              <Th sortable>Name</Th><Th sortable>Type</Th><Th>Chain address</Th><Th align="right">Chain ID</Th><Th align="right" sortable>Updated</Th><Th align="right">Actions</Th>
            </div>
            {filtered.length === 0 ? (
              <EmptyState icon="settings" title="No modules match" body="Adjust the filter or search." secondary={{ label: "Show all", onClick: () => { setFilter("all"); setQ(""); } }} />
            ) : filtered.map((m, i) => (
              <div key={m.id} className="adm-table-row" style={{ display: "grid", gridTemplateColumns: "1.6fr 120px 160px 120px 120px 90px", gap: "var(--space-16)", padding: "var(--space-16) var(--space-20)", alignItems: "center", borderTop: i === 0 ? "none" : "1px solid var(--border)" }}>
                <span style={{ font: '500 14px/20px "Inter", sans-serif', color: "var(--fg)" }}>{m.name}</span>
                <span><span className="chip chip--neutral" style={{ padding: "1px var(--space-8)", fontSize: 11 }}>{m.type}</span></span>
                <span className="addr" style={{ font: '400 12px/16px "JetBrains Mono", monospace', color: "var(--fg-muted)" }}>{m.addr}</span>
                <span className="tnum" style={{ textAlign: "right", font: '400 13px "Inter", sans-serif', color: "var(--fg-muted)" }}>{m.chainId}</span>
                <span className="tnum" style={{ textAlign: "right", font: '400 13px "Inter", sans-serif', color: "var(--fg-muted)" }}>{fmtDate(m.updated)}</span>
                <div style={{ display: "flex", justifyContent: "flex-end" }}>
                  <button className="btn btn--secondary btn--sm" type="button" style={{ color: "var(--danger)" }} onClick={() => onAction("delete-module", m)}>Delete</button>
                </div>
              </div>
            ))}
          </div>
        </section>
      </div>
    </div>
  );
};

window.AdminModuleManagement = AdminModuleManagement;
