"use client";
/** Workspace security policy (admins): 2FA requirement & allowed methods, IP allowlist, password policy, alerts, sessions, member recovery. */
import { useEffect, useState } from "react";
import { AlertTriangle, ShieldCheck } from "lucide-react";
import { Badge, Button, Card, Checkbox, Field, Input, PageHeader, Select, Spinner, Stat, Textarea, Toggle, api, useAction, useUI } from "@/components/ui";
import { ago, fmtDate, useApi } from "@/components/hooks";

type Policy = { mfaRequired: boolean; allowedMfaMethods: string[]; ipAllowlist: string[]; passwordMinLength: number; loginAlerts: boolean; trustedDeviceDays: number; sessionTimeoutMinutes: number };
type Overview = {
  policy: Policy; coverage: number; yourIp: string | null; delivery: { email: boolean; sms: boolean };
  members: { id: string; name: string; email: string; mfaEnabled: boolean; methods: string[]; locked: boolean; lastLoginAt: string | null; status: string }[];
  events: { id: string; action: string; actorName: string | null; ip: string | null; at: string; after: Record<string, unknown> | null }[];
};
const METHOD_LABEL: Record<string, string> = { webauthn: "Passkey / security key", totp: "Authenticator app", sms: "SMS code", email: "Email code" };
const EVENT_TONE: Record<string, string> = { login_failed: "amber", mfa_failed: "amber", account_locked: "red", login_blocked_locked: "red", mfa_reset_by_admin: "violet", security_policy_updated: "violet" };

export default function SecurityPolicyPage() {
  const o = useApi<{ data: Overview }>("/security/overview");
  const [p, setP] = useState<Policy | null>(null);
  const [ips, setIps] = useState("");
  const { busy, run } = useAction();
  const { push } = useUI();
  useEffect(() => { if (o.data) { setP(o.data.data.policy); setIps(o.data.data.policy.ipAllowlist.join("\n")); } }, [o.data]);
  if (o.error) return <p className="text-[13px] text-ink-3">Only workspace admins can manage the security policy.</p>;
  if (!o.data || !p) return <Spinner />;
  const d = o.data.data;
  const save = (confirmIpLockout = false): Promise<unknown> => run(async (): Promise<unknown> => {
    try {
      await api("/security/policy", { method: "PATCH", body: { ...p, ipAllowlist: ips.split(/[\n,]/).map((x) => x.trim()).filter(Boolean), confirmIpLockout } });
      o.reload(); push("ok", "Security policy saved");
    } catch (e) {
      if ((e as { code?: string }).code === "would_lock_out" && confirm(`${(e as Error).message}\n\nSave anyway?`)) return save(true);
      throw e;
    }
  });
  const member = (path: string, ok: string) => run(async () => { await api(path, { body: {} }); o.reload(); }, ok);

  return (
    <>
      <PageHeader title="Security policy" subtitle="Applies to everyone in this workspace" actions={<Button variant="primary" loading={busy} onClick={() => save()}>Save policy</Button>} />
      <div className="mb-4 grid grid-cols-2 gap-3 lg:grid-cols-4">
        <Stat label="Members with 2FA" value={`${d.coverage}%`} sub={`${d.members.filter((m) => m.mfaEnabled).length} of ${d.members.length}`} icon={<ShieldCheck className="h-4 w-4" />} />
        <Stat label="Locked accounts" value={d.members.filter((m) => m.locked).length} />
        <Stat label="Failed sign-ins (recent)" value={d.events.filter((e) => e.action === "login_failed" || e.action === "mfa_failed").length} />
        <Stat label="Your IP" value={<span className="text-[15px]">{d.yourIp ?? "unknown"}</span>} />
      </div>
      <div className="grid gap-4 xl:grid-cols-2">
        <Card title="Two-factor authentication">
          <div className="space-y-3 text-[13px]">
            <Toggle checked={p.mfaRequired} onChange={(v) => setP({ ...p, mfaRequired: v })} label="Require two-factor for every member" />
            <Field label="Allowed methods" hint="Passkeys and authenticator apps are the strongest. SMS is convenient but weaker against SIM-swap.">
              <div className="grid gap-1.5 sm:grid-cols-2">{["webauthn", "totp", "sms", "email"].map((m) => (
                <Checkbox key={m} checked={p.allowedMfaMethods.includes(m)} onChange={(v) => setP({ ...p, allowedMfaMethods: v ? [...p.allowedMfaMethods, m] : p.allowedMfaMethods.filter((x) => x !== m) })}
                  label={<span>{METHOD_LABEL[m]}{(m === "sms" && !d.delivery.sms) || (m === "email" && !d.delivery.email) ? <span className="text-ink-3"> · provider not configured</span> : null}</span>} />
              ))}</div>
            </Field>
            <Field label="Trust a device for" hint="Members can skip the second step on a personal device for this long. 0 = always ask."><Select value={String(p.trustedDeviceDays)} onChange={(e) => setP({ ...p, trustedDeviceDays: Number(e.target.value) })}><option value="0">Never — always ask</option><option value="7">7 days</option><option value="14">14 days</option><option value="30">30 days</option><option value="90">90 days</option></Select></Field>
          </div>
        </Card>
        <Card title="Sign-in & sessions">
          <div className="space-y-3 text-[13px]">
            <Field label="Minimum password length"><Input type="number" min={10} max={64} value={p.passwordMinLength} onChange={(e) => setP({ ...p, passwordMinLength: Number(e.target.value) })} /></Field>
            <Field label="Session timeout"><Select value={String(p.sessionTimeoutMinutes)} onChange={(e) => setP({ ...p, sessionTimeoutMinutes: Number(e.target.value) })}><option value="60">1 hour</option><option value="480">8 hours</option><option value="1440">1 day</option><option value="10080">7 days</option><option value="43200">30 days</option></Select></Field>
            <Toggle checked={p.loginAlerts} onChange={(v) => setP({ ...p, loginAlerts: v })} label="Email members when they sign in from a new device" />
            <p className="text-[12px] text-ink-3">Always on: account lock for 15 minutes after 8 wrong passwords, breached-password check, rate limits on sign-in and codes.</p>
          </div>
        </Card>
        <Card title="IP allowlist" subtitle="Only these networks can open this workspace. Leave empty to allow any network." className="xl:col-span-2">
          <div className="grid gap-3 md:grid-cols-[1fr_280px]">
            <Textarea rows={4} value={ips} onChange={(e) => setIps(e.target.value)} placeholder={"One per line, e.g.\n103.4.145.10\n103.4.145.0/24"} className="font-mono text-[12.5px]" />
            <div className="flex gap-2 rounded-[10px] bg-warn/10 p-3 text-[12px] text-warn"><AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" /><span>Add your office and VPN addresses before saving. Your current IP is <b>{d.yourIp ?? "unknown"}</b>. Members on other networks will be signed out of this workspace.</span></div>
          </div>
        </Card>
        <Card title="Members" className="xl:col-span-2" bodyClass="p-0 overflow-x-auto">
          <table className="table-mac min-w-[720px]"><thead><tr><th>Member</th><th>Two-factor</th><th>Last sign-in</th><th className="text-right">Actions</th></tr></thead>
            <tbody>{d.members.map((m) => (
              <tr key={m.id}>
                <td><div className="font-medium">{m.name}</div><div className="text-[11.5px] text-ink-3">{m.email}</div></td>
                <td>{m.mfaEnabled ? <span className="flex flex-wrap gap-1">{m.methods.map((x) => <Badge key={x} tone="green">{METHOD_LABEL[x] ?? x}</Badge>)}</span> : <Badge tone={p.mfaRequired ? "red" : "amber"}>Not set up</Badge>}{m.locked && <Badge tone="red" className="ml-1">Locked</Badge>}</td>
                <td className="text-ink-3">{m.lastLoginAt ? ago(m.lastLoginAt) : "never"}</td>
                <td className="text-right"><span className="inline-flex gap-1.5">
                  {m.locked && <Button size="sm" onClick={() => member(`/users/${m.id}/unlock`, "Account unlocked")}>Unlock</Button>}
                  {m.mfaEnabled && <Button size="sm" onClick={() => { if (confirm(`Reset two-factor for ${m.name}? They will be signed out and must set it up again. Only do this after confirming their identity.`)) member(`/users/${m.id}/mfa/reset`, "Two-factor reset"); }}>Reset 2FA</Button>}
                  <Button size="sm" variant="ghost" onClick={() => member(`/users/${m.id}/sessions/revoke`, "Signed out everywhere")}>Sign out</Button>
                </span></td>
              </tr>
            ))}</tbody>
          </table>
        </Card>
        <Card title="Recent security events" className="xl:col-span-2" bodyClass="p-0">
          <ul className="max-h-[360px] divide-y divide-line/60 overflow-y-auto">{d.events.map((e) => (
            <li key={e.id} className="flex flex-wrap items-center gap-2 px-4 py-2 text-[12.5px]"><Badge tone={EVENT_TONE[e.action] ?? "gray"}>{e.action.replace(/_/g, " ")}</Badge><span className="font-medium">{e.actorName}</span>{e.after && (e.after.method || e.after.mfa) ? <span className="text-ink-3">{String(e.after.method ?? e.after.mfa)}</span> : null}<span className="ml-auto text-ink-3">{e.ip ?? ""} · {fmtDate(e.at)}</span></li>
          ))}{!d.events.length && <li className="px-4 py-3 text-[12.5px] text-ink-3">No events yet.</li>}</ul>
        </Card>
      </div>
    </>
  );
}
