/* Settings bundle — API keys, Webhooks, Team
   All three are sub-tabs of /settings (and reachable individually). */

const SettingsPage = ({ initialTab = "api-keys", pushToast }) => {
  const [tab, setTab] = React.useState(initialTab);
  return (
    <>
      <header className="page-header">
        <div className="page-header__inner">
          <div className="page-header__eyebrow">Workspace · Settings</div>
          <h1>Settings</h1>
          <p className="page-header__sub">Manage API access, webhooks, redaction rules, and team members for {SCENARIO.tenant.name}.</p>
        </div>
      </header>

      <Tabs
        items={[
          { value: "api-keys", label: "API keys" },
          { value: "webhooks", label: "Webhooks" },
          { value: "redaction", label: "Redaction rules" },
          { value: "team", label: "Team" },
          { value: "billing", label: "Billing" },
        ]}
        value={tab}
        onChange={setTab}
      />

      {tab === "api-keys" && <APIKeysTab pushToast={pushToast} />}
      {tab === "webhooks" && <WebhooksTab pushToast={pushToast} />}
      {tab === "redaction" && <RedactionTab />}
      {tab === "team" && <TeamTab pushToast={pushToast} />}
      {tab === "billing" && <BillingTab />}
    </>
  );
};

/* -------- API keys -------- */
const KEYS = [
  { name: "Production · Encounter Summary", prefix: "af_live_x3k", created: "2026-05-01", last: "2 min ago", status: "active", scope: "Full access" },
  { name: "Staging", prefix: "af_test_8nm", created: "2026-05-15", last: "1 hr ago", status: "active", scope: "Read · write" },
  { name: "CI / GitHub Actions", prefix: "af_live_4hp", created: "2026-06-10", last: "Never", status: "unused", scope: "Read only" },
  { name: "Legacy prod (rotated)", prefix: "af_live_1aa", created: "2026-04-22", last: "—", status: "revoked", scope: "—" },
];

const APIKeysTab = ({ pushToast }) => {
  const [showNew, setShowNew] = React.useState(false);
  const [revealKey, setRevealKey] = React.useState(null);
  const [newKey, setNewKey] = React.useState({ name: "", scope: "rw" });
  const [revoking, setRevoking] = React.useState(null);

  const createKey = () => {
    setShowNew(false);
    setRevealKey({ name: newKey.name, value: "af_live_x3k2qz9a8mn4lp2rt7yvWERrt22aaPP9xKk", prefix: "af_live_x3k" });
  };

  return (
    <div className="col gap-4">
      <Card title="Active API keys" meta="3 active · 1 revoked"
        padded={false}
        action={<Button variant="primary" size="sm" icon={window.Icon.plus({ size: 12 })} onClick={() => { setNewKey({ name: "", scope: "rw" }); setShowNew(true); }}>New key</Button>}
      >
        <table className="table">
          <thead>
            <tr><th>Name</th><th>Prefix</th><th>Scope</th><th>Created</th><th>Last used</th><th>Status</th><th style={{ width: 80 }}></th></tr>
          </thead>
          <tbody>
            {KEYS.map((k) => (
              <tr key={k.prefix}>
                <td className="fw-500">{k.name}</td>
                <td><HashChip value={k.prefix + "…rt7yv"} short={k.prefix + "…"} /></td>
                <td className="text-sm">{k.scope}</td>
                <td className="text-sm muted">{k.created}</td>
                <td className="text-sm muted">{k.last}</td>
                <td>
                  {k.status === "active" && <Badge tone="sealed" icon={window.Icon.checkSimple({ size: 11 })}>Active</Badge>}
                  {k.status === "unused" && <Badge tone="partial" icon={window.Icon.warning({ size: 11 })}>Unused 30d</Badge>}
                  {k.status === "revoked" && <Badge tone="contra" icon={window.Icon.xCircle({ size: 11 })}>Revoked</Badge>}
                </td>
                <td>
                  {k.status === "active" && <Button variant="ghost" size="sm" onClick={() => setRevoking(k)}>Revoke</Button>}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      <div className="card card--padded settings-tips">
        <div className="text-xs muted fw-600" style={{ letterSpacing: "0.08em", textTransform: "uppercase", fontFamily: "var(--font-mono)", marginBottom: 6 }}>Key hygiene</div>
        <ul className="settings-tips__list">
          <li>Rotate production keys every 90 days. We surface unused keys after 30 days.</li>
          <li>Keys never leave your secret manager — Attestia stores only a salted prefix + scope.</li>
          <li>Revocation is instant; in-flight requests fail with <span className="mono text-xs">401 · key revoked</span>.</li>
        </ul>
      </div>

      {/* New key modal */}
      <Modal open={showNew} onClose={() => setShowNew(false)} title="Generate a new API key"
        sub="Shown once. Store it in your secret manager immediately."
        wide
        footer={
          <>
            <Button variant="ghost" onClick={() => setShowNew(false)}>Cancel</Button>
            <Button variant="primary" disabled={!newKey.name} onClick={createKey} icon={window.Icon.key({ size: 12 })}>Generate</Button>
          </>
        }
      >
        <div className="col gap-4">
          <Field label="Key name" required hint="Used to identify this key in logs.">
            <input className="input" placeholder="e.g. Production · Discharge Bot" value={newKey.name} onChange={(e) => setNewKey({ ...newKey, name: e.target.value })} autoFocus />
          </Field>
          <Field label="Scope" hint="Use the narrowest scope that works.">
            <div className="radio-row">
              <RadioCard selected={newKey.scope === "r"} title="Read only" sub="GET traces, sources, packs" onClick={() => setNewKey({ ...newKey, scope: "r" })} />
              <RadioCard selected={newKey.scope === "rw"} title="Read · write" sub="Wrap calls + manage resources" onClick={() => setNewKey({ ...newKey, scope: "rw" })} />
              <RadioCard selected={newKey.scope === "full"} title="Full access" sub="Includes settings + team" onClick={() => setNewKey({ ...newKey, scope: "full" })} />
            </div>
          </Field>
        </div>
      </Modal>

      {/* Reveal-once modal */}
      <Modal open={!!revealKey} onClose={() => setRevealKey(null)} title="Your new API key"
        sub="This is the only time we'll show the full key. Copy it now."
        wide
        footer={<Button variant="primary" onClick={() => { setRevealKey(null); pushToast({ kind: "success", title: "Key generated", sub: revealKey?.name }); }}>I've saved it · Done</Button>}
      >
        <div className="col gap-4">
          <div className="reveal-key">
            <div className="reveal-key__label mono">{revealKey?.name}</div>
            <div className="reveal-key__row">
              <span className="mono">{revealKey?.value}</span>
              <Button variant="ghost" size="sm" icon={window.Icon.copy({ size: 12 })} onClick={() => pushToast({ kind: "success", title: "Key copied" })}>Copy</Button>
            </div>
          </div>
          <div className="onb-note" style={{ background: "var(--contra-soft)", borderColor: "rgba(155, 44, 44, 0.25)" }}>
            <span style={{ color: "var(--contra)" }}>{window.Icon.alertTriangle({ size: 14 })}</span>
            <div className="text-sm" style={{ color: "var(--ink-1)" }}>
              <strong>Won't be shown again.</strong> If you lose it, generate a new key and revoke this one. Anyone with this key can wrap calls as your tenant.
            </div>
          </div>
        </div>
      </Modal>

      {/* Revoke modal — type to confirm */}
      <RevokeModal target={revoking} onClose={() => setRevoking(null)} onDone={(k) => { setRevoking(null); pushToast({ kind: "warn", title: "Key revoked", sub: k.name }); }} />
    </div>
  );
};

const RevokeModal = ({ target, onClose, onDone }) => {
  const [confirm, setConfirm] = React.useState("");
  React.useEffect(() => { setConfirm(""); }, [target]);
  if (!target) return null;
  return (
    <Modal open={!!target} onClose={onClose} title={`Revoke ${target.name}?`}
      sub="In-flight requests using this key will fail. This cannot be undone."
      footer={
        <>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button variant="destructive" disabled={confirm !== "revoke"} onClick={() => onDone(target)} icon={window.Icon.xCircle({ size: 13 })}>
            Revoke key
          </Button>
        </>
      }
    >
      <div className="col gap-4">
        <div className="onb-note" style={{ background: "var(--contra-soft)", borderColor: "rgba(155, 44, 44, 0.25)" }}>
          <span style={{ color: "var(--contra)" }}>{window.Icon.alertTriangle({ size: 14 })}</span>
          <div className="text-sm">
            Prefix <span className="mono">{target.prefix}…</span> · last used {target.last}.
          </div>
        </div>
        <Field label={<span>Type <span className="mono">revoke</span> to confirm</span>}>
          <input className="input mono" value={confirm} onChange={(e) => setConfirm(e.target.value)} placeholder="revoke" />
        </Field>
      </div>
    </Modal>
  );
};

/* -------- Webhooks -------- */
const ENDPOINTS = [
  { url: "https://meridian.health/attestia/hooks", events: ["verification.failed", "evidence.signed", "share.created"], status: "active", last: "200 · 14ms" },
  { url: "https://staging.meridian.health/hooks", events: ["verification.failed"], status: "testing", last: "—" },
];

const DELIVERIES = [
  { time: "10:34", event: "verification.failed", endpoint: "meridian.health/attestia/hooks", status: 200, latency: 14 },
  { time: "10:30", event: "evidence.signed", endpoint: "meridian.health/attestia/hooks", status: 200, latency: 22 },
  { time: "10:25", event: "share.created", endpoint: "meridian.health/attestia/hooks", status: 200, latency: 18 },
  { time: "09:12", event: "verification.failed", endpoint: "meridian.health/attestia/hooks", status: 503, latency: null, retried: true },
  { time: "09:11", event: "verification.failed", endpoint: "meridian.health/attestia/hooks", status: 200, latency: 31 },
];

const WebhooksTab = ({ pushToast }) => (
  <div className="col gap-4">
    <Card title="Endpoints" padded={false}
      action={<Button variant="primary" size="sm" icon={window.Icon.plus({ size: 12 })}>Add endpoint</Button>}
    >
      <table className="table">
        <thead><tr><th>URL</th><th>Events</th><th>Status</th><th>Last delivery</th><th style={{ width: 50 }}></th></tr></thead>
        <tbody>
          {ENDPOINTS.map((e) => (
            <tr key={e.url} className="clickable">
              <td className="mono text-sm">{e.url}</td>
              <td>
                <div className="row gap-1" style={{ flexWrap: "wrap" }}>
                  {e.events.map((ev) => <span key={ev} className="event-chip mono">{ev}</span>)}
                </div>
              </td>
              <td>
                {e.status === "active" && <Badge tone="sealed" icon={window.Icon.checkSimple({ size: 11 })}>Active</Badge>}
                {e.status === "testing" && <Badge tone="partial" icon={window.Icon.warning({ size: 11 })}>Testing</Badge>}
              </td>
              <td className="mono text-xs muted">{e.last}</td>
              <td style={{ color: "var(--ink-4)" }}>{window.Icon.chevronRight({ size: 13 })}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </Card>

    <Card title="Recent deliveries" meta="Last 30 days · 2,847 events" padded={false}
      action={<Button variant="ghost" size="sm" icon={window.Icon.zap({ size: 12 })} onClick={() => pushToast({ kind: "success", title: "Test event sent", sub: "evidence.signed · 200 OK · 22ms" })}>Send test event</Button>}
    >
      <table className="table">
        <thead><tr><th>Time</th><th>Event</th><th>Endpoint</th><th>Status</th><th>Latency</th></tr></thead>
        <tbody>
          {DELIVERIES.map((d, i) => (
            <tr key={i} className="clickable">
              <td className="mono text-xs muted">{d.time}</td>
              <td><span className="event-chip mono">{d.event}</span></td>
              <td className="mono text-xs">{d.endpoint}</td>
              <td>
                {d.status === 200 && <Badge tone="sealed">200 OK</Badge>}
                {d.status === 503 && <span><Badge tone="contra">503</Badge> {d.retried && <Badge tone="partial">retried</Badge>}</span>}
              </td>
              <td className="mono text-sm muted">{d.latency ? `${d.latency}ms` : "—"}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </Card>
  </div>
);

/* -------- Redaction rules -------- */
const RULE_PACKS = [
  { id: "hipaa18", name: "HIPAA · 18 identifiers", desc: "Names, addresses, dates, phone, email, SSN, MRN, account #, certificate #, vehicle ID, device ID, URLs, IPs, biometric, full-face photos, other unique IDs.", count: 18, enabled: true, locked: true },
  { id: "phi-deid", name: "PHI · Safe-harbor de-identification", desc: "Removes all 18 identifiers + dates beyond year; ages 90+ collapsed.", count: 19, enabled: true },
  { id: "pci", name: "PCI · Card data", desc: "PAN, CVV, expiry, track data, cardholder name when adjacent.", count: 5, enabled: false },
  { id: "custom-internal", name: "Custom · Meridian patient names", desc: "Tenant-defined regex for internal patient-name patterns.", count: 1, enabled: true, custom: true },
];

const RedactionTab = () => (
  <div className="col gap-4">
    <div className="card card--padded">
      <div className="text-xs muted fw-600" style={{ letterSpacing: "0.08em", textTransform: "uppercase", fontFamily: "var(--font-mono)" }}>Active redaction</div>
      <div style={{ fontFamily: "var(--font-display)", fontStyle: "italic", fontSize: 26, marginTop: 4, color: "var(--ink-1)" }}>
        Nothing reaches the LLM without passing this filter.
      </div>
      <div className="text-sm muted" style={{ marginTop: 6 }}>
        Detected identifiers are replaced with deterministic surrogates (e.g. <span className="mono">[PATIENT_NAME_1]</span>) and original spans are hashed for audit.
      </div>
    </div>

    <Card title="Rule packs" padded={false}>
      <div>
        {RULE_PACKS.map((p) => (
          <div key={p.id} className="rule-row">
            <label className="rule-row__toggle">
              <input type="checkbox" defaultChecked={p.enabled} disabled={p.locked} />
              <span className={`rule-toggle ${p.enabled ? "rule-toggle--on" : ""}`} />
            </label>
            <div className="rule-row__body">
              <div className="row gap-2">
                <span className="fw-600">{p.name}</span>
                {p.locked && <Badge tone="info" icon={window.Icon.lock({ size: 10 })}>Required by HIPAA preset</Badge>}
                {p.custom && <Badge tone="neutral">Custom</Badge>}
                <span className="muted mono text-xs">{p.count} identifiers</span>
              </div>
              <div className="text-xs muted" style={{ marginTop: 4 }}>{p.desc}</div>
            </div>
            <Button variant="ghost" size="sm" iconRight={window.Icon.chevronRight({ size: 12 })}>Configure</Button>
          </div>
        ))}
      </div>
    </Card>

    <Card title="Custom regex · test playground" padded>
      <div className="col gap-3">
        <Field label="Pattern (Python regex)">
          <input className="input mono" defaultValue={"(?:MRN|MR#|Medical Record)\\s*[:#]?\\s*([A-Z0-9-]{6,12})"} />
        </Field>
        <Field label="Test text">
          <textarea className="textarea mono" rows="3" defaultValue={"Patient MRN: ACME-228194-A presents with new-onset HFrEF. Record # 9847-2 confirmed by Dr. Lee."} />
        </Field>
        <div className="row gap-2">
          <Button variant="secondary" size="sm" icon={window.Icon.zap({ size: 12 })}>Run match</Button>
          <span className="text-xs muted">2 matches · ACME-228194-A · 9847-2</span>
        </div>
      </div>
    </Card>
  </div>
);

/* -------- Team -------- */
const MEMBERS = [
  { name: "Priya Sharma", email: "priya@meridian.health", role: "Admin", joined: "Apr 12", lastActive: "now", initials: "PS" },
  { name: "Mike Chen", email: "mike@meridian.health", role: "Engineer", joined: "Apr 15", lastActive: "12m ago", initials: "MC" },
  { name: "Dr. Aisha Patel", email: "a.patel@meridian.health", role: "Compliance", joined: "May 01", lastActive: "2h ago", initials: "AP" },
  { name: "R. Chen (HIPAA Audit Partners)", email: "r.chen@hipaa-audit-partners.com", role: "Auditor (RO)", joined: "Sep 22", lastActive: "—", initials: "RC", external: true },
];

const ROLES = [
  { id: "admin", title: "Admin", sub: "Full access · billing · team" },
  { id: "engineer", title: "Engineer", sub: "Apps · API keys · webhooks · traces · sources" },
  { id: "compliance", title: "Compliance", sub: "Compliance dashboards · evidence packs · redaction · traces (read)" },
  { id: "auditor", title: "Auditor (RO)", sub: "Read-only across the tenant; cannot edit anything" },
];

const TeamTab = ({ pushToast }) => {
  const [invite, setInvite] = React.useState(false);
  const [inviteForm, setInviteForm] = React.useState({ email: "", role: "compliance" });

  return (
    <div className="col gap-4">
      <Card title={`${MEMBERS.length} members`} meta="1 admin · 1 engineer · 1 compliance · 1 external auditor"
        padded={false}
        action={<Button variant="primary" size="sm" icon={window.Icon.plus({ size: 12 })} onClick={() => { setInviteForm({ email: "", role: "compliance" }); setInvite(true); }}>Invite member</Button>}
      >
        <table className="table">
          <thead><tr><th>Member</th><th>Email</th><th>Role</th><th>Joined</th><th>Last active</th><th style={{ width: 50 }}></th></tr></thead>
          <tbody>
            {MEMBERS.map((m) => (
              <tr key={m.email}>
                <td>
                  <div className="row gap-2">
                    <div className="avatar" style={{ width: 28, height: 28 }}>{m.initials}</div>
                    <div>
                      <div className="fw-500">{m.name}</div>
                      {m.external && <div className="text-xs muted">External · {m.email.split("@")[1]}</div>}
                    </div>
                  </div>
                </td>
                <td className="text-sm muted mono">{m.email}</td>
                <td>
                  <Badge tone={m.role.includes("Auditor") ? "info" : m.role === "Admin" ? "sealed" : "neutral"}>
                    {m.role}
                  </Badge>
                </td>
                <td className="text-sm muted">{m.joined}, 2026</td>
                <td className="text-sm muted">{m.lastActive}</td>
                <td><Button variant="ghost" size="sm">⋯</Button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      <Card title="Pending invitations" padded={false}>
        <div className="empty-row">
          <span className="muted text-sm">No pending invitations.</span>
        </div>
      </Card>

      <Modal open={invite} onClose={() => setInvite(false)} title="Invite a teammate"
        sub="They'll receive an email with a one-time signup link valid 7 days."
        wide
        footer={
          <>
            <Button variant="ghost" onClick={() => setInvite(false)}>Cancel</Button>
            <Button variant="primary" disabled={!inviteForm.email} onClick={() => { setInvite(false); pushToast({ kind: "success", title: "Invitation sent", sub: `${inviteForm.email} · ${ROLES.find((r) => r.id === inviteForm.role)?.title}` }); }} icon={window.Icon.share({ size: 12 })}>
              Send invite
            </Button>
          </>
        }
      >
        <div className="col gap-4">
          <Field label="Email" required>
            <input className="input" placeholder="teammate@meridian.health" value={inviteForm.email} onChange={(e) => setInviteForm({ ...inviteForm, email: e.target.value })} autoFocus />
          </Field>
          <Field label="Role" hint="Scoped to the principle of least privilege.">
            <div className="col gap-2">
              {ROLES.map((r) => (
                <label key={r.id} className={`role-card ${inviteForm.role === r.id ? "role-card--selected" : ""}`}>
                  <input type="radio" checked={inviteForm.role === r.id} onChange={() => setInviteForm({ ...inviteForm, role: r.id })} style={{ display: "none" }} />
                  <span className="role-card__radio">{inviteForm.role === r.id && <span />}</span>
                  <div>
                    <div className="fw-600 text-sm">{r.title}</div>
                    <div className="text-xs muted" style={{ marginTop: 2 }}>{r.sub}</div>
                  </div>
                </label>
              ))}
            </div>
          </Field>
        </div>
      </Modal>
    </div>
  );
};

/* -------- Billing -------- */
const BillingTab = () => (
  <div className="col gap-4">
    <div className="card card--padded">
      <div className="row gap-2" style={{ alignItems: "flex-end", justifyContent: "space-between" }}>
        <div>
          <div className="text-xs muted fw-600" style={{ letterSpacing: "0.08em", textTransform: "uppercase", fontFamily: "var(--font-mono)" }}>Current plan</div>
          <div style={{ fontFamily: "var(--font-display)", fontStyle: "italic", fontSize: 32, marginTop: 4, color: "var(--ink-1)" }}>Healthcare · Growth</div>
          <div className="text-sm muted" style={{ marginTop: 4 }}>$1,499/month · billed monthly · next bill Dec 1, 2026 · BAA in place</div>
        </div>
        <Button variant="secondary" size="sm">Manage plan</Button>
      </div>
    </div>

    <Card title="Usage this period" padded>
      <div className="col gap-4">
        <UsageRow label="Verify calls" used={62420} max={100000} unit="calls" />
        <UsageRow label="Sources" used={4} max={25} unit="sources" />
        <UsageRow label="Storage" used={0.8} max={5} unit="GB" />
        <UsageRow label="Sandbox CPU-hours" used={42} max={100} unit="CPU-hrs" cost="$14.20 estimated" />
      </div>
    </Card>

    <Card title="Invoices" padded={false}>
      <table className="table">
        <thead><tr><th>Date</th><th>Description</th><th>Amount</th><th>Status</th><th></th></tr></thead>
        <tbody>
          {[
            { d: "Nov 01, 2026", n: "Growth · monthly", a: "$1,499.00", s: "paid" },
            { d: "Oct 01, 2026", n: "Growth · monthly", a: "$1,499.00", s: "paid" },
            { d: "Sep 01, 2026", n: "Growth · monthly", a: "$1,499.00", s: "paid" },
          ].map((inv, i) => (
            <tr key={i}>
              <td className="text-sm">{inv.d}</td>
              <td className="fw-500">{inv.n}</td>
              <td className="mono tabular">{inv.a}</td>
              <td><Badge tone="sealed" icon={window.Icon.checkSimple({ size: 11 })}>Paid</Badge></td>
              <td><Button variant="ghost" size="sm" icon={window.Icon.download({ size: 12 })}>PDF</Button></td>
            </tr>
          ))}
        </tbody>
      </table>
    </Card>
  </div>
);

const UsageRow = ({ label, used, max, unit, cost }) => {
  const pct = (used / max) * 100;
  return (
    <div className="usage-row">
      <div className="row gap-2" style={{ marginBottom: 6 }}>
        <span className="fw-500">{label}</span>
        <span className="spacer" />
        <span className="mono tabular text-sm">{used.toLocaleString()} / {max.toLocaleString()} {unit}</span>
        {cost && <span className="text-xs muted">· {cost}</span>}
      </div>
      <div className="progress">
        <div className="progress__bar" style={{ width: `${pct}%`, background: pct > 80 ? "var(--partial)" : "var(--ink-1)" }} />
      </div>
    </div>
  );
};

window.SettingsPage = SettingsPage;
