// AdminCompliance.jsx — Compliance controls + audit log.
//   · Real actions: pause/unpause facility, freeze/unfreeze user, clawback —
//     each mutates mock state, fires a toast, and appends to the audit log.
//   · A-1: every timestamp renders through fmtDateTime ("Jun 1, 2026 · 9:15 AM UTC").
//   · C-4: one hero metric + hairline strip, not four equal cards.

const ACTION_BADGE = {
  FREEZE:   { bg: "var(--red-10)",   fg: "var(--red-80)" },
  UNFREEZE: { bg: "var(--green-10)", fg: "var(--green-80)" },
  PAUSE:    { bg: "var(--gold-10)",  fg: "var(--gold-80)" },
  UNPAUSE:  { bg: "var(--green-10)", fg: "var(--green-80)" },
  CLAWBACK: { bg: "var(--red-10)",   fg: "var(--red-80)" },
  APPROVE:  { bg: "var(--green-10)", fg: "var(--green-80)" },
  REJECT:   { bg: "var(--red-10)",   fg: "var(--red-80)" },
  REVOKE:   { bg: "var(--red-10)",   fg: "var(--red-80)" },
};
const ActionBadge = ({ action }) => {
  const c = ACTION_BADGE[action] || { bg: "var(--black-10)", fg: "var(--black-80)" };
  return <span style={{ display: "inline-block", padding: "2px 9px", borderRadius: 999, background: c.bg, color: c.fg, font: '600 11px/16px "Inter", sans-serif', letterSpacing: "0.03em" }}>{action}</span>;
};

const ComplianceForm = ({ facilities, accounts, onAction }) => {
  const [tab, setTab] = React.useState("facilities");
  const [target, setTarget] = React.useState("");
  const [reason, setReason] = React.useState("");

  const tabs = [
    { key: "facilities", label: "Facilities", icon: "shield" },
    { key: "users", label: "Users", icon: "accounts" },
    { key: "clawback", label: "Clawback", icon: "clawback" },
  ];
  const cfg = {
    facilities: { selectLabel: "Select facility", placeholder: "Search facilities by name or ID…", btn: "Pause facility", btnTone: "warning", actionKey: "form-pause-facility" },
    users:      { selectLabel: "Select account", placeholder: "Search accounts by wallet or ID…", btn: "Freeze account", btnTone: "danger", actionKey: "form-freeze-account" },
    clawback:   { selectLabel: "Select account", placeholder: "Search accounts by wallet or ID…", btn: "Initiate clawback", btnTone: "danger", actionKey: "form-clawback" },
  }[tab];
  const options = tab === "facilities"
    ? facilities.map(f => ({ id: f.id, label: f.name }))
    : accounts.map(a => ({ id: a.id, label: `${a.id} · ${a.facility}` }));

  const submit = () => {
    if (!target || !reason.trim()) return;
    onAction(cfg.actionKey, { targetId: target, targetLabel: (options.find(o => o.id === target) || {}).label, reason: reason.trim() });
    setTarget(""); setReason("");
  };
  const btnStyle = cfg.btnTone === "danger"
    ? { background: "var(--danger)", color: "var(--white-100)" }
    : { background: "var(--gold-10)", color: "var(--gold-80)", border: "1.5px solid var(--gold-60)" };

  return (
    <section className="card" data-annot-note="real action → toast + audit append">
      <SectionHeader eyebrow="Controls" title="Compliance controls" />
      <div style={{ font: '400 13px/20px "Inter", sans-serif', color: "var(--fg-subtle)", marginTop: -8, marginBottom: 18 }}>
        Manage global facility and user compliance status. Actions are recorded in the audit log.
      </div>

      <div style={{ display: "inline-flex", padding: 4, background: "var(--bg-alt)", borderRadius: 10, marginBottom: 20, border: "1px solid var(--border)" }}>
        {tabs.map(t => (
          <button key={t.key} type="button" onClick={() => { setTab(t.key); setTarget(""); }} style={{
            all: "unset", cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 7,
            padding: "7px 14px", borderRadius: 7, font: '500 13px/18px "Inter", sans-serif',
            color: tab === t.key ? "var(--fg)" : "var(--fg-subtle)",
            background: tab === t.key ? "var(--surface)" : "transparent",
            boxShadow: tab === t.key ? "0 1px 2px rgba(0,0,0,0.05)" : "none",
          }}><Icon name={t.icon} size={14} stroke={1.6}/> {t.label}</button>
        ))}
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 18, maxWidth: 720 }}>
        <div>
          <label style={{ display: "block", font: '500 13px/18px "Inter", sans-serif', color: "var(--fg)", marginBottom: 8 }}>{cfg.selectLabel}</label>
          <select value={target} onChange={(e) => setTarget(e.target.value)} style={{
            width: "100%", height: 40, padding: "0 12px", borderRadius: 8, border: "1px solid var(--border-strong)",
            background: "var(--surface)", color: target ? "var(--fg)" : "var(--fg-subtle)", font: '400 14px "Inter", sans-serif',
          }}>
            <option value="">{cfg.placeholder}</option>
            {options.map(o => <option key={o.id} value={o.id}>{o.label}</option>)}
          </select>
        </div>
        <div>
          <label style={{ display: "block", font: '500 13px/18px "Inter", sans-serif', color: "var(--fg)", marginBottom: 8 }}>Reason</label>
          <input value={reason} onChange={(e) => setReason(e.target.value)} placeholder="Provide a reason for this action…" style={{
            width: "100%", height: 40, padding: "0 12px", borderRadius: 8, border: "1px solid var(--border-strong)",
            background: "var(--surface)", color: "var(--fg)", font: '400 14px "Inter", sans-serif', boxSizing: "border-box",
          }} />
        </div>
        <button type="button" onClick={submit} disabled={!target || !reason.trim()} style={{
          height: 44, borderRadius: 8, border: "none", cursor: (!target || !reason.trim()) ? "not-allowed" : "pointer",
          font: '600 14px "Inter", sans-serif', opacity: (!target || !reason.trim()) ? 0.5 : 1,
          transition: "opacity var(--motion-fast)", ...btnStyle,
        }}>{cfg.btn}</button>
      </div>
    </section>
  );
};

const AuditLog = ({ entries }) => {
  const [actionFilter, setActionFilter] = React.useState("all");
  const [statusFilter, setStatusFilter] = React.useState("all");
  const [q, setQ] = React.useState("");
  const filtered = entries.filter(e =>
    (actionFilter === "all" || e.action === actionFilter) &&
    (statusFilter === "all" || e.status === statusFilter) &&
    (q === "" || e.target.toLowerCase().includes(q.toLowerCase()) || e.description.toLowerCase().includes(q.toLowerCase()))
  );
  return (
    <section className="card" style={{ padding: 0 }} data-annot-note="A-1 single date format">
      <div style={{ padding: "20px 24px 16px" }}>
        <SectionHeader eyebrow="Audit" title="Audit log" count={entries.length} />
        <div style={{ font: '400 13px/20px "Inter", sans-serif', color: "var(--fg-subtle)", marginTop: -8 }}>
          History of all compliance actions and interventions.
        </div>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 16, alignItems: "center" }}>
          <SegmentControl value={actionFilter} onChange={setActionFilter} options={[
            { value: "all", label: "All actions" }, { value: "PAUSE", label: "Pause" },
            { value: "FREEZE", label: "Freeze" }, { value: "UNPAUSE", label: "Unpause" }, { value: "CLAWBACK", label: "Clawback" },
          ]} />
          <SegmentControl value={statusFilter} onChange={setStatusFilter} options={[
            { value: "all", label: "All statuses" }, { value: "executed", label: "Executed" },
            { value: "pending", label: "Pending" }, { value: "reverted", label: "Reverted" },
          ]} />
        </div>
        <div style={{ marginTop: 12 }}><SearchBox placeholder="Search audit log…" value={q} onChange={setQ} width="100%" /></div>
      </div>
      <div className="adm-scroll">
        <div className="adm-table-head" style={{ display: "grid", gridTemplateColumns: "130px 120px 150px 1fr 230px", gap: 14, padding: "10px 24px", background: "var(--bg-alt)", borderTop: "1px solid var(--border)", borderBottom: "1px solid var(--border)" }}>
          <Th sortable>Action</Th><Th sortable>Status</Th><Th sortable>Target</Th><Th sortable>Description</Th><Th align="right" sortable>Timestamp</Th>
        </div>
        {filtered.length === 0 ? (
          <EmptyState icon="search" title="No matching entries" body="Adjust the filters or search above." secondary={{ label: "Clear filters", onClick: () => { setActionFilter("all"); setStatusFilter("all"); setQ(""); } }} />
        ) : filtered.map((e, i) => (
          <div key={e.id} className="adm-table-row" style={{ display: "grid", gridTemplateColumns: "130px 120px 150px 1fr 230px", gap: 14, padding: "14px 24px", alignItems: "center", borderTop: i === 0 ? "none" : "1px solid var(--border)" }}>
            <div><ActionBadge action={e.action} /></div>
            <div><AdminStatus status={e.status} /></div>
            <span className="addr" style={{ font: '500 13px/18px "JetBrains Mono", monospace', color: "var(--fg)" }}>{e.target}</span>
            <span style={{ font: '400 13px/18px "Inter", sans-serif', color: "var(--fg)" }}>{e.description}</span>
            <span className="tnum" style={{ textAlign: "right", font: '400 13px/18px "Inter", sans-serif', color: "var(--fg-muted)" }} title={fmtRelative(e.ts)}>{fmtDateTime(e.ts)}</span>
          </div>
        ))}
      </div>
    </section>
  );
};

const AdminCompliance = ({ facilities, accounts, totals, auditLog, onAction, onNavigate, state, onRetry }) => {
  if (state === "loading") return <PageSkeleton shape="rows" />;
  if (state === "error")   return <PageError title="Couldn't load compliance controls" onRetry={onRetry} />;
  const totalTvl = facilities.reduce((s, f) => s + f.tvl, 0);
  const avgUtil = (facilities.reduce((s, f) => s + f.utilization, 0) / facilities.length).toFixed(1);
  const atRisk = totals.warn + totals.default;

  // Mini audit strip — last 5 entries + link to full log
  const recentAudit = auditLog.slice(0, 5);
  const AB_MINI = { FREEZE: "var(--red-80)", UNFREEZE: "var(--success)", PAUSE: "var(--gold-80)", UNPAUSE: "var(--success)", CLAWBACK: "var(--red-80)", APPROVE: "var(--success)", REJECT: "var(--red-80)", REVOKE: "var(--red-80)" };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
      <PageHeader eyebrow="Risk & liquidations" title="Compliance controls" icon="shieldCheck"
        lede="Manage global facility and user compliance status." annot="C-5 sentence case" />
      <HeroStrip
        hero={{ label: "Total value locked", value: fmtMoneyShort(totalTvl), sub: "Across all facilities under compliance control" }}
        supports={[
          { label: "Utilization rate", value: `${avgUtil}%`, sub: "Target 80%" },
          { label: "At-risk positions", value: atRisk, sub: `${totals.default} in default — action required`, tone: "danger" },
          { label: "Avg health factor", value: totals.avgHF.toFixed(2), sub: totals.avgHF < 1.5 ? "Caution" : "Healthy", tone: totals.avgHF < 1.5 ? "warning" : "success" },
        ]}
      />
      <ComplianceForm facilities={facilities} accounts={accounts} onAction={onAction} />

      {/* Recent actions — mini strip, full log is a first-class nav item */}
      <section className="card" style={{ padding: 0 }}>
        <div style={{ padding: "20px 24px 16px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <div>
            <Eyebrow>Audit</Eyebrow>
            <h2 className="section-heading" style={{ marginTop: 6, fontSize: 20, lineHeight: "26px" }}>Recent actions</h2>
          </div>
          <button className="btn btn--text" type="button" onClick={() => onNavigate && onNavigate("audit")}>
            View full audit log <Icon name="arrow" size={13} stroke={1.6} />
          </button>
        </div>
        <div>
          {recentAudit.map((e, i) => (
            <div key={e.id} style={{ display: "grid", gridTemplateColumns: "120px 100px 1fr 1fr 160px", gap: 14, padding: "12px 24px", alignItems: "center", borderTop: "1px solid var(--border)" }}>
              <span style={{ display: "inline-block", padding: "2px 9px", borderRadius: 999, background: "var(--bg-alt)", color: AB_MINI[e.action] || "var(--fg-subtle)", font: '600 11px/16px "Inter", sans-serif' }}>{e.action}</span>
              <div><AdminStatus status={e.status} /></div>
              <span className="addr" style={{ font: '500 12px/16px "JetBrains Mono", monospace', color: "var(--fg-muted)" }}>{e.target}</span>
              <span style={{ font: '400 12px/16px "Inter", sans-serif', color: "var(--fg)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{e.description}</span>
              <span className="tnum" style={{ textAlign: "right", font: '400 12px/16px "Inter", sans-serif', color: "var(--fg-subtle)" }} title={fmtDateTime(e.ts)}>{fmtRelative(e.ts)}</span>
            </div>
          ))}
        </div>
      </section>
    </div>
  );
};

window.AdminCompliance = AdminCompliance;
