"use client";
/** Profile & security: password, two-factor methods (passkey, authenticator app, SMS, email), backup codes, trusted devices, sessions. */
import { useSearchParams } from "next/navigation";
import { Suspense, useEffect, useState, type ReactNode } from "react";
import { Copy, Download, KeyRound, LifeBuoy, LogOut, Mail, MessageSquare, Monitor, ShieldCheck, Smartphone, Trash2 } from "lucide-react";
import { Badge, Button, Card, Empty, Field, Input, PageHeader, Select, Sheet, Spinner, api, cx, useAction, useUI } from "@/components/ui";
import { ago, useApi } from "@/components/hooks";

type MType = "totp" | "email" | "sms" | "webauthn";
type Sec = {
  email: string; phone: string | null; hasPassword: boolean; mfaEnabled: boolean; mfaRequired: boolean;
  methods: { id: string; type: MType; label: string; target: string | null; lastUsedAt: string | null; createdAt: string }[];
  backupCodesLeft: number; allowedMethods: MType[]; delivery: { email: boolean; sms: boolean };
  trustedDevices: { id: string; userAgent: string | null; ip: string | null; expiresAt: string; lastUsedAt: string | null; createdAt: string }[];
  sessions: { id: string; userAgent: string | null; ip: string | null; createdAt: string; lastSeenAt: string | null; mfaMethod: string | null; current: boolean }[];
};
const META: Record<MType, { icon: ReactNode; title: string; desc: string }> = {
  webauthn: { icon: <KeyRound className="h-5 w-5" />, title: "Passkey or security key", desc: "Fingerprint, Face ID, Windows Hello, device PIN, or a YubiKey. Strongest and phishing-resistant." },
  totp: { icon: <Smartphone className="h-5 w-5" />, title: "Authenticator app", desc: "Google Authenticator, Microsoft Authenticator, Authy, 1Password — works offline." },
  sms: { icon: <MessageSquare className="h-5 w-5" />, title: "Text message (SMS)", desc: "A 6-digit code to your mobile number." },
  email: { icon: <Mail className="h-5 w-5" />, title: "Email code", desc: "A 6-digit code to your email address." },
};
const device = (ua: string | null) => {
  if (!ua) return "Unknown device";
  const os = /Windows/.test(ua) ? "Windows" : /Android/.test(ua) ? "Android" : /iPhone|iPad/.test(ua) ? "iOS" : /Mac OS/.test(ua) ? "macOS" : /Linux/.test(ua) ? "Linux" : "Device";
  const br = /Edg\//.test(ua) ? "Edge" : /OPR\//.test(ua) ? "Opera" : /Chrome\//.test(ua) ? "Chrome" : /Firefox\//.test(ua) ? "Firefox" : /Safari\//.test(ua) ? "Safari" : "Browser";
  return `${br} on ${os}`;
};

export default function SecurityPage() {
  return <Suspense fallback={<Spinner />}><Security /></Suspense>;
}

function Security() {
  const sp = useSearchParams();
  const me = useApi<{ data: { user: any } }>("/me");
  const sec = useApi<{ data: Sec }>("/me/security");
  const [profile, setProfile] = useState({ name: "", locale: "en" });
  const [pw, setPw] = useState({ current: "", next: "" });
  const [adding, setAdding] = useState<MType | null>(null);
  const [codes, setCodes] = useState<string[] | null>(null);
  const [confirm, setConfirm] = useState<{ title: string; action: (password: string) => Promise<void> } | null>(null);
  const { busy, run } = useAction();
  const { push } = useUI();
  useEffect(() => { if (me.data?.data.user) setProfile({ name: me.data.data.user.name, locale: me.data.data.user.locale ?? "en" }); }, [me.data]);
  if (!me.data || !sec.data) return <Spinner />;
  const s = sec.data.data;
  const has = (t: MType) => s.methods.some((m) => m.type === t);
  const reload = () => { sec.reload(); me.reload(); };
  const onCodes = (c: string[] | null | undefined) => { if (c?.length) setCodes(c); };

  return (
    <>
      <PageHeader title="Profile & security" subtitle={s.email} />
      {(sp.get("enforce") || s.mfaRequired) && !s.mfaEnabled && <p className="mb-4 rounded-[9px] bg-warn/10 px-3 py-2 text-[13px] text-warn">This workspace requires two-factor authentication. Add at least one method below to continue using the app.</p>}

      <Card className="mb-4" title={<span className="flex items-center gap-2"><ShieldCheck className="h-4 w-4 text-brand" />Two-factor authentication {s.mfaEnabled ? <Badge tone="green">On</Badge> : <Badge tone="amber">Off</Badge>}</span>}
        subtitle="Add more than one method so you are never locked out. You choose which one to use each time you sign in.">
        {s.methods.length > 0 && (
          <ul className="mb-4 divide-y divide-line/60 rounded-[10px] border border-line">
            {s.methods.map((m) => (
              <li key={m.id} className="flex flex-wrap items-center gap-3 px-3 py-2.5 text-[13px]">
                <span className="text-brand">{META[m.type].icon}</span>
                <div className="min-w-0 flex-1"><div className="font-medium">{m.label}{m.target ? <span className="font-normal text-ink-3"> · {m.target}</span> : null}</div><div className="text-[11.5px] text-ink-3">{META[m.type].title} · added {ago(m.createdAt)}{m.lastUsedAt ? ` · last used ${ago(m.lastUsedAt)}` : ""}</div></div>
                <Button size="sm" variant="ghost" icon={<Trash2 className="h-3.5 w-3.5" />} onClick={() => setConfirm({ title: `Remove “${m.label}”?`, action: async (password) => { await api(`/me/mfa/${m.id}/remove`, { body: { password } }); reload(); push("ok", "Method removed"); } })}>Remove</Button>
              </li>
            ))}
          </ul>
        )}
        <div className="grid gap-2 md:grid-cols-2">
          {(["webauthn", "totp", "sms", "email"] as MType[]).map((t) => {
            const allowed = s.allowedMethods.includes(t);
            const deliveryOff = (t === "sms" && !s.delivery.sms) || (t === "email" && !s.delivery.email);
            return (
              <button key={t} disabled={!allowed || deliveryOff} onClick={() => setAdding(t)} className={cx("flex items-start gap-3 rounded-[10px] border border-line p-3 text-left hover:border-brand/60 hover:bg-brand/5", (!allowed || deliveryOff) && "cursor-not-allowed opacity-50 hover:border-line hover:bg-transparent")}>
                <span className="mt-0.5 text-brand">{META[t].icon}</span>
                <span className="min-w-0"><span className="block text-[13.5px] font-semibold">{has(t) ? "Add another: " : "Add: "}{META[t].title}</span><span className="block text-[12px] text-ink-3">{!allowed ? "Not allowed by your workspace policy" : deliveryOff ? `${t === "sms" ? "SMS" : "Email"} sending isn't configured on this server yet` : META[t].desc}</span></span>
              </button>
            );
          })}
        </div>
        {s.mfaEnabled && (
          <div className="mt-4 flex flex-wrap items-center gap-3 rounded-[10px] bg-sunken/70 px-3 py-2.5 text-[13px]">
            <LifeBuoy className="h-4 w-4 text-ink-3" />
            <span className="flex-1"><b>Backup codes</b> — {s.backupCodesLeft} of 10 left. Each works once if you lose your phone or key.</span>
            <Button size="sm" onClick={() => setConfirm({ title: "Generate new backup codes? Old codes will stop working.", action: async (password) => { const r = await api<{ data: { codes: string[] } }>("/me/mfa/backup-codes", { body: { password } }); setCodes(r.data.codes); reload(); } })}>Generate new codes</Button>
          </div>
        )}
      </Card>

      <div className="grid gap-4 xl:grid-cols-2">
        <Card title="Profile">
          <div className="space-y-3">
            <Field label="Name"><Input value={profile.name} onChange={(e) => setProfile({ ...profile, name: e.target.value })} /></Field>
            <Field label="Interface language"><Select value={profile.locale} onChange={(e) => setProfile({ ...profile, locale: e.target.value })}><option value="en">English</option><option value="bn">বাংলা</option></Select></Field>
            <Button variant="primary" loading={busy} onClick={() => run(async () => { await api("/me", { method: "PATCH", body: profile }); location.reload(); }, "Profile saved")}>Save profile</Button>
          </div>
        </Card>
        <Card title="Change password" subtitle="Changing it signs you out of every other device and forgets trusted devices">
          <div className="space-y-3">
            <Field label="Current password"><Input type="password" autoComplete="current-password" value={pw.current} onChange={(e) => setPw({ ...pw, current: e.target.value })} /></Field>
            <Field label="New password" hint="At least 10 characters with letters and numbers. Passwords found in known data breaches are refused."><Input type="password" autoComplete="new-password" value={pw.next} onChange={(e) => setPw({ ...pw, next: e.target.value })} /></Field>
            <Button loading={busy} onClick={() => run(async () => { await api("/me/password", { body: pw }); setPw({ current: "", next: "" }); reload(); }, "Password changed — other sessions signed out")}>Change password</Button>
          </div>
        </Card>
        <Card title="Where you're signed in" actions={s.sessions.length > 1 ? <Button size="sm" icon={<LogOut className="h-3.5 w-3.5" />} onClick={() => run(async () => { await api("/me/sessions/revoke-others", { body: {} }); sec.reload(); }, "Signed out everywhere else")}>Sign out others</Button> : null} bodyClass="p-0">
          <ul className="divide-y divide-line/60">{s.sessions.map((x) => (
            <li key={x.id} className="flex items-center gap-3 px-4 py-2.5 text-[13px]">
              <Monitor className="h-4 w-4 text-ink-3" />
              <div className="min-w-0 flex-1"><div className="font-medium">{device(x.userAgent)} {x.current && <Badge tone="green">This device</Badge>}</div><div className="text-[11.5px] text-ink-3">{x.ip ?? "unknown IP"} · signed in {ago(x.createdAt)}{x.lastSeenAt ? ` · active ${ago(x.lastSeenAt)}` : ""}{x.mfaMethod ? ` · verified by ${x.mfaMethod.replace("_", " ")}` : ""}</div></div>
              {!x.current && <Button size="sm" variant="ghost" onClick={() => run(async () => { await api(`/me/sessions/${x.id}/revoke`, { body: {} }); sec.reload(); }, "Session signed out")}>Sign out</Button>}
            </li>
          ))}</ul>
        </Card>
        <Card title="Trusted devices" subtitle="Devices that skip the second step until they expire" actions={s.trustedDevices.length ? <Button size="sm" onClick={() => run(async () => { await api("/me/trusted-devices/revoke-all", { body: {} }); sec.reload(); }, "All devices forgotten")}>Forget all</Button> : null} bodyClass="p-0">
          {!s.trustedDevices.length ? <div className="p-4"><Empty title="No trusted devices">Tick “Trust this device” when you verify to skip the second step on a personal device.</Empty></div> : (
            <ul className="divide-y divide-line/60">{s.trustedDevices.map((d) => (
              <li key={d.id} className="flex items-center gap-3 px-4 py-2.5 text-[13px]"><Monitor className="h-4 w-4 text-ink-3" /><div className="min-w-0 flex-1"><div className="font-medium">{device(d.userAgent)}</div><div className="text-[11.5px] text-ink-3">{d.ip ?? ""} · trusted {ago(d.createdAt)} · expires {ago(d.expiresAt)}</div></div><Button size="sm" variant="ghost" onClick={() => run(async () => { await api(`/me/trusted-devices/${d.id}`, { method: "DELETE" }); sec.reload(); }, "Device forgotten")}>Forget</Button></li>
            ))}</ul>
          )}
        </Card>
      </div>

      {adding && <AddMethod type={adding} sec={s} onClose={() => setAdding(null)} onDone={(c) => { setAdding(null); reload(); onCodes(c); push("ok", "Two-factor method added"); }} />}
      {codes && <BackupCodes codes={codes} onClose={() => setCodes(null)} />}
      {confirm && <ConfirmPassword title={confirm.title} hasPassword={s.hasPassword} onClose={() => setConfirm(null)} onConfirm={async (p) => { await confirm.action(p); setConfirm(null); }} />}
    </>
  );
}

function AddMethod({ type, sec, onClose, onDone }: { type: MType; sec: Sec; onClose: () => void; onDone: (codes?: string[] | null) => void }) {
  const [step, setStep] = useState<"start" | "verify">("start");
  const [target, setTarget] = useState(type === "email" ? sec.email : sec.phone ?? "");
  const [label, setLabel] = useState("");
  const [state, setState] = useState<{ methodId?: string; challengeId?: string; secret?: string; qr?: string; sentTo?: string }>({});
  const [code, setCode] = useState("");
  const { busy, run } = useAction();

  const start = () => run(async () => {
    if (type === "totp") {
      const d = (await api<{ data: { methodId: string; secret: string; otpauth: string } }>("/me/mfa/totp", { body: { label: label || undefined } })).data;
      const QR = await import("qrcode");
      setState({ methodId: d.methodId, secret: d.secret, qr: await QR.toDataURL(d.otpauth, { margin: 1, width: 220 }) });
      setStep("verify");
    } else if (type === "email" || type === "sms") {
      const d = (await api<{ data: { methodId: string; challengeId: string; sentTo: string } }>(`/me/mfa/${type}`, { body: type === "email" ? { email: target } : { phone: target } })).data;
      setState(d); setStep("verify");
    } else {
      const { startRegistration, browserSupportsWebAuthn } = await import("@simplewebauthn/browser");
      if (!browserSupportsWebAuthn()) throw new Error("This browser doesn't support passkeys or security keys");
      const optionsJSON = (await api<{ data: any }>("/me/mfa/webauthn/options", { body: {} })).data;
      const response = await startRegistration({ optionsJSON });
      const r = await api<{ data: { backupCodes: string[] | null } }>("/me/mfa/webauthn/verify", { body: { response, label: label || undefined } });
      onDone(r.data.backupCodes);
    }
  });
  const verify = () => run(async () => {
    const r = type === "totp"
      ? await api<{ data: { backupCodes: string[] | null } }>(`/me/mfa/totp/${state.methodId}/verify`, { body: { code } })
      : await api<{ data: { backupCodes: string[] | null } }>(`/me/mfa/${state.methodId}/verify-code`, { body: { challengeId: state.challengeId, code } });
    onDone(r.data.backupCodes);
  });
  const resend = () => run(async () => { const r = await api<{ data: { challengeId: string } }>(`/me/mfa/${state.methodId}/resend`, { body: {} }); setState({ ...state, challengeId: r.data.challengeId }); }, "New code sent");

  return (
    <Sheet open onClose={onClose} title={META[type].title} width={460}>
      <div className="space-y-4 text-[13px]">
        <p className="text-ink-2">{META[type].desc}</p>
        {step === "start" ? (
          <>
            {(type === "webauthn" || type === "totp") && <Field label="Name (optional)"><Input value={label} onChange={(e) => setLabel(e.target.value)} placeholder={type === "webauthn" ? "e.g. MacBook Touch ID, YubiKey" : "e.g. Work phone"} maxLength={60} /></Field>}
            {type === "email" && <Field label="Email address"><Input type="email" value={target} onChange={(e) => setTarget(e.target.value)} /></Field>}
            {type === "sms" && <Field label="Mobile number" hint="Bangladesh numbers like 01712-345678 are converted automatically"><Input type="tel" value={target} onChange={(e) => setTarget(e.target.value)} placeholder="+8801…" /></Field>}
            <Button variant="primary" loading={busy} onClick={start} icon={META[type].icon}>{type === "webauthn" ? "Create passkey / register key" : type === "totp" ? "Show QR code" : "Send code"}</Button>
          </>
        ) : (
          <>
            {type === "totp" && <>
              <p>Scan this QR code with your authenticator app, or enter the key manually.</p>
              {state.qr && <img alt="QR code for your authenticator app" className="h-48 w-48 rounded-[8px] bg-white p-2" src={state.qr} />}
              <code className="block break-all rounded bg-sunken p-2 text-[12px]">{state.secret}</code>
            </>}
            {(type === "email" || type === "sms") && <p>We sent a 6-digit code to <b>{state.sentTo}</b>. <button className="text-brand underline" onClick={resend}>Resend</button></p>}
            <Field label="6-digit code"><Input autoFocus autoComplete="one-time-code" inputMode="numeric" maxLength={6} value={code} onChange={(e) => setCode(e.target.value.replace(/\D/g, ""))} className="font-mono tracking-[0.3em]" /></Field>
            <Button variant="primary" loading={busy} disabled={code.length !== 6} onClick={verify}>Verify & turn on</Button>
          </>
        )}
      </div>
    </Sheet>
  );
}

function BackupCodes({ codes, onClose }: { codes: string[]; onClose: () => void }) {
  const { push } = useUI();
  const text = `Tempest Pulse backup codes — each works once\n\n${codes.join("\n")}\n`;
  return (
    <Sheet open onClose={onClose} title="Save your backup codes" width={420} footer={<div className="flex justify-end"><Button variant="primary" onClick={onClose}>I've saved them</Button></div>}>
      <div className="space-y-3 text-[13px]">
        <p className="text-ink-2">Store these somewhere safe (a password manager or printed). Each code works once if you lose access to your other methods. <b>They won't be shown again.</b></p>
        <div className="grid grid-cols-2 gap-2 rounded-[10px] bg-sunken p-3 font-mono text-[14px]">{codes.map((c) => <span key={c}>{c}</span>)}</div>
        <div className="flex gap-2">
          <Button icon={<Copy className="h-3.5 w-3.5" />} onClick={() => navigator.clipboard?.writeText(text).then(() => push("ok", "Copied"))}>Copy</Button>
          <Button icon={<Download className="h-3.5 w-3.5" />} onClick={() => { const a = document.createElement("a"); a.href = URL.createObjectURL(new Blob([text], { type: "text/plain" })); a.download = "tempest-pulse-backup-codes.txt"; a.click(); }}>Download</Button>
        </div>
      </div>
    </Sheet>
  );
}

function ConfirmPassword({ title, hasPassword, onClose, onConfirm }: { title: string; hasPassword: boolean; onClose: () => void; onConfirm: (password: string) => Promise<void> }) {
  const [p, setP] = useState("");
  const { busy, run } = useAction();
  return (
    <Sheet open onClose={onClose} title="Confirm it's you" width={400} footer={<div className="flex justify-end gap-2"><Button onClick={onClose}>Cancel</Button><Button variant="primary" loading={busy} onClick={() => run(() => onConfirm(p))}>Confirm</Button></div>}>
      <div className="space-y-3 text-[13px]">
        <p>{title}</p>
        {hasPassword ? <Field label="Current password"><Input type="password" autoFocus autoComplete="current-password" value={p} onChange={(e) => setP(e.target.value)} /></Field> : <p className="text-ink-3">You signed in with Google — this works within 15 minutes of signing in.</p>}
      </div>
    </Sheet>
  );
}
