"use client";
/** Sign-in second step: passkey / security key, authenticator app, SMS code, email code or a backup code. */
import { useEffect, useState } from "react";
import { KeyRound, Mail, MessageSquare, ShieldCheck, Smartphone, LifeBuoy } from "lucide-react";
import { Button, Checkbox, Field, Input, Spinner, api, cx } from "./ui";

type M = { id: string; type: "totp" | "email" | "sms" | "webauthn"; label: string; target: string | null; allowed: boolean };
type Opts = { methods: M[]; backupCodes: number; rememberDays: number; email: string };
const ICON = { webauthn: <KeyRound className="h-4 w-4" />, totp: <Smartphone className="h-4 w-4" />, sms: <MessageSquare className="h-4 w-4" />, email: <Mail className="h-4 w-4" /> };
const ORDER = { webauthn: 0, totp: 1, sms: 2, email: 3 } as const;

export function MfaLogin() {
  const [opts, setOpts] = useState<Opts | null>(null);
  const [pick, setPick] = useState<string | "backup" | null>(null);
  const [code, setCode] = useState("");
  const [challenge, setChallenge] = useState<{ id: string; sentTo: string | null } | null>(null);
  const [remember, setRemember] = useState(false);
  const [err, setErr] = useState("");
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    api<Opts>("/api/auth/mfa-options", { body: {} }).then((o) => {
      setOpts(o);
      const first = [...o.methods].filter((m) => m.allowed).sort((a, b) => ORDER[a.type] - ORDER[b.type])[0];
      setPick(first?.id ?? (o.backupCodes ? "backup" : null));
    }).catch((e) => { setErr((e as Error).message); if (/expired|sign in/i.test((e as Error).message)) setTimeout(() => (window.location.href = "/login"), 1500); });
  }, []);

  const method = opts?.methods.find((m) => m.id === pick) ?? null;
  const done = (next: string) => { window.location.href = next; };
  const fail = (e: unknown) => { setErr((e as Error).message); setBusy(false); };

  const choose = (id: string | "backup") => { setPick(id); setCode(""); setChallenge(null); setErr(""); };
  const send = async () => {
    if (!method) return;
    setBusy(true); setErr("");
    try { const r = await api<{ challengeId: string; sentTo: string | null }>("/api/auth/mfa-send", { body: { methodId: method.id } }); setChallenge({ id: r.challengeId, sentTo: r.sentTo }); } catch (e) { setErr((e as Error).message); }
    setBusy(false);
  };
  const passkey = async () => {
    setBusy(true); setErr("");
    try {
      const { startAuthentication, browserSupportsWebAuthn } = await import("@simplewebauthn/browser");
      if (!browserSupportsWebAuthn()) throw new Error("This browser doesn't support passkeys — choose another method");
      const optionsJSON = await api("/api/auth/mfa-webauthn-options", { body: {} });
      const response = await startAuthentication({ optionsJSON });
      const r = await api<{ next: string }>("/api/auth/mfa-webauthn", { body: { response, remember } });
      done(r.next);
    } catch (e) { fail(e); }
  };
  const verify = async (e: React.FormEvent) => {
    e.preventDefault(); setBusy(true); setErr("");
    try {
      const r = await api<{ next: string }>("/api/auth/mfa", { body: pick === "backup" ? { code, backup: true, remember } : { code, methodId: method?.id, challengeId: challenge?.id, remember } });
      done(r.next);
    } catch (x) { fail(x); }
  };

  if (!opts) return <div className="flex justify-center py-6">{err ? <p className="text-[13px] text-bad">{err}</p> : <Spinner />}</div>;
  const usable = [...opts.methods].sort((a, b) => ORDER[a.type] - ORDER[b.type]);
  return (
    <div className="space-y-4">
      {usable.length + (opts.backupCodes ? 1 : 0) > 1 && (
        <div className="flex flex-wrap gap-1.5" role="tablist" aria-label="Verification method">
          {usable.map((m) => (
            <button key={m.id} type="button" role="tab" aria-selected={pick === m.id} disabled={!m.allowed} onClick={() => choose(m.id)} title={m.allowed ? undefined : "Not allowed in this workspace"}
              className={cx("inline-flex items-center gap-1.5 rounded-full border px-3 py-1.5 text-[12.5px]", pick === m.id ? "border-brand bg-brand/10 text-brand" : "border-line hover:bg-sunken", !m.allowed && "opacity-40")}>
              {ICON[m.type]}{m.label}
            </button>
          ))}
          {opts.backupCodes > 0 && <button type="button" role="tab" aria-selected={pick === "backup"} onClick={() => choose("backup")} className={cx("inline-flex items-center gap-1.5 rounded-full border px-3 py-1.5 text-[12.5px]", pick === "backup" ? "border-brand bg-brand/10 text-brand" : "border-line hover:bg-sunken")}><LifeBuoy className="h-4 w-4" />Backup code</button>}
        </div>
      )}

      {method?.type === "webauthn" ? (
        <div className="space-y-3 text-center">
          <p className="text-[13px] text-ink-2">Use your fingerprint, face, device PIN or security key.</p>
          <Remember days={opts.rememberDays} value={remember} onChange={setRemember} />
          <Button variant="primary" size="lg" className="w-full" loading={busy} onClick={passkey} icon={<KeyRound className="h-4 w-4" />}>Use passkey or security key</Button>
        </div>
      ) : (method?.type === "email" || method?.type === "sms") && !challenge ? (
        <div className="space-y-3">
          <p className="text-[13px] text-ink-2">We'll send a 6-digit code {method.type === "sms" ? "by SMS to" : "by email to"} <b>{method.target}</b>.</p>
          <Button variant="primary" size="lg" className="w-full" loading={busy} onClick={send} icon={ICON[method.type]}>Send code</Button>
        </div>
      ) : pick ? (
        <form className="space-y-3" onSubmit={verify}>
          {challenge && <p className="text-[12.5px] text-ink-2">Code sent to <b>{challenge.sentTo}</b>. It expires in 10 minutes. <button type="button" className="text-brand underline" onClick={send}>Resend</button></p>}
          <Field label={pick === "backup" ? `Backup code (${opts.backupCodes} left)` : method?.type === "totp" ? "6-digit code from your authenticator app" : "6-digit code"}>
            <Input autoFocus autoComplete="one-time-code" inputMode={pick === "backup" ? "text" : "numeric"} maxLength={pick === "backup" ? 9 : 6} value={code}
              onChange={(e) => setCode(pick === "backup" ? e.target.value.toUpperCase().replace(/[^A-Z0-9-]/g, "") : e.target.value.replace(/\D/g, ""))}
              className="text-center font-mono text-[20px] tracking-[0.35em]" placeholder={pick === "backup" ? "XXXX-XXXX" : "000000"} />
          </Field>
          <Remember days={opts.rememberDays} value={remember} onChange={setRemember} />
          <Button variant="primary" size="lg" className="w-full" loading={busy} type="submit" disabled={code.length < 6}>Verify</Button>
        </form>
      ) : (
        <p className="text-[13px] text-ink-2">No usable verification method. Ask your workspace admin to reset your two-factor authentication.</p>
      )}
      {err && <p className="rounded-[7px] bg-bad/10 px-3 py-2 text-[12.5px] text-bad" role="alert">{err}</p>}
      <p className="flex items-center gap-1.5 text-[11.5px] text-ink-3"><ShieldCheck className="h-3.5 w-3.5" />Lost access to your methods? Use a backup code, or ask your admin to reset two-factor for {opts.email}.</p>
    </div>
  );
}

function Remember({ days, value, onChange }: { days: number; value: boolean; onChange: (v: boolean) => void }) {
  if (!days) return null;
  return <Checkbox checked={value} onChange={onChange} label={<span className="text-[12.5px]">Trust this device for {days} days (don't use on shared computers)</span>} />;
}
