"use client";
/** Password recovery: email or mobile → 6-digit code → new password. */
import { useState } from "react";
import { ArrowLeft, Eye, EyeOff, KeyRound } from "lucide-react";
import { Button, Field, Input, api } from "./ui";

export function ForgotForm() {
  const [step, setStep] = useState<"ask" | "reset">("ask");
  const [identifier, setIdentifier] = useState("");
  const [reset, setReset] = useState<{ resetId: string; channel: string; sentTo: string } | null>(null);
  const [code, setCode] = useState("");
  const [password, setPassword] = useState("");
  const [show, setShow] = useState(false);
  const [err, setErr] = useState("");
  const [busy, setBusy] = useState(false);

  const send = async (e?: React.FormEvent) => {
    e?.preventDefault(); setBusy(true); setErr("");
    try { const r = await api("/api/auth/forgot-start", { body: { identifier } }); setReset(r); setStep("reset"); } catch (x) { setErr((x as Error).message); }
    setBusy(false);
  };
  const submit = async (e: React.FormEvent) => {
    e.preventDefault(); setBusy(true); setErr("");
    try { const r = await api("/api/auth/forgot-reset", { body: { resetId: reset!.resetId, code, password } }); window.location.href = r.next; } catch (x) { setErr((x as Error).message); setBusy(false); }
  };

  return step === "ask" ? (
    <form className="space-y-3" onSubmit={send}>
      <Field label="Email or mobile number" hint="We'll send a 6-digit code to reset your password"><Input required autoFocus value={identifier} onChange={(e) => setIdentifier(e.target.value)} placeholder="you@company.com or 01712 345678" className="h-11" /></Field>
      {err && <p className="rounded-[12px] bg-bad/10 px-3 py-2 text-[12.5px] text-bad" role="alert">{err}</p>}
      <Button variant="primary" size="lg" className="w-full" loading={busy} type="submit" icon={<KeyRound className="h-4 w-4" />}>Send reset code</Button>
      <a href="/login" className="flex items-center justify-center gap-1 text-[13px] text-ink-2 hover:text-brand"><ArrowLeft className="h-3.5 w-3.5" />Back to sign in</a>
    </form>
  ) : (
    <form className="space-y-3" onSubmit={submit}>
      <p className="rounded-[12px] bg-brand/5 px-3 py-2 text-[12.5px] text-ink-2">If an account exists for <b>{reset?.sentTo}</b>, a code is on its way {reset?.channel === "sms" ? "by SMS" : "by email"}. It expires in 15 minutes.</p>
      <Field label="6-digit code"><Input required autoFocus autoComplete="one-time-code" inputMode="numeric" maxLength={6} value={code} onChange={(e) => setCode(e.target.value.replace(/\D/g, ""))} className="h-11 text-center font-mono text-[18px] tracking-[.35em]" placeholder="000000" /></Field>
      <Field label="New password" hint="At least 10 characters with letters and numbers">
        <div className="relative"><Input required type={show ? "text" : "password"} autoComplete="new-password" value={password} onChange={(e) => setPassword(e.target.value)} className="h-11 pr-9" />
          <button type="button" onClick={() => setShow(!show)} className="absolute right-3 top-1/2 -translate-y-1/2 text-ink-3" aria-label={show ? "Hide password" : "Show password"}>{show ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}</button></div>
      </Field>
      {err && <p className="rounded-[12px] bg-bad/10 px-3 py-2 text-[12.5px] text-bad" role="alert">{err}</p>}
      <Button variant="primary" size="lg" className="w-full" loading={busy} type="submit" disabled={code.length !== 6}>Set new password</Button>
      <div className="flex justify-between text-[12.5px]"><button type="button" className="text-ink-2 hover:text-brand" onClick={() => { setStep("ask"); setCode(""); }}>Use a different email or number</button><button type="button" className="text-brand hover:underline" onClick={() => send()}>Resend code</button></div>
      <p className="text-[11.5px] text-ink-3">Resetting signs you out on every device. Two-factor stays on for your next sign-in.</p>
    </form>
  );
}
