"use client"; import { useRef, useState } from "react"; import { signIn } from "next-auth/react"; import { useRouter } from "next/navigation"; import { Button } from "@/app/shadcn_components/ui/button"; import { Input } from "@/app/shadcn_components/ui/input"; const RESEND_COOLDOWN_MS = 30_000; type VerifyStatus = "idle" | "verifying"; type ResendStatus = "idle" | "resending" | "cooldown"; export default function VerifyCodeForm({ email }: { email: string }) { const router = useRouter(); const [code, setCode] = useState(""); const [verifyStatus, setVerifyStatus] = useState("idle"); const [resendStatus, setResendStatus] = useState("idle"); const [error, setError] = useState(null); const [resendNotice, setResendNotice] = useState(null); const inFlightRef = useRef(false); const isWorking = verifyStatus === "verifying" || resendStatus === "resending"; async function submitCode(value: string) { if (inFlightRef.current) return; if (!/^\d{6}$/.test(value)) return; inFlightRef.current = true; setVerifyStatus("verifying"); setError(null); const res = await signIn("email-code", { email, code: value, redirect: false, }); inFlightRef.current = false; if (res?.ok) { router.push("/home"); return; } setVerifyStatus("idle"); setCode(""); setError( "That code didn't match. Check the latest email — older codes stop working as soon as you request a new one.", ); } function handleChange(next: string) { const digits = next.replace(/\D/g, "").slice(0, 6); setCode(digits); if (error) setError(null); if (resendNotice) setResendNotice(null); if (digits.length === 6) void submitCode(digits); } async function handleResend() { if (isWorking || resendStatus === "cooldown" || !email) return; setResendStatus("resending"); setError(null); setResendNotice(null); const res = await signIn("email", { email, redirect: false }); if (res?.error) { setResendStatus("idle"); setError( "We couldn't send a new code right now. Wait a minute and try again.", ); return; } setResendNotice("A new code is on its way. Older codes stop working."); setResendStatus("cooldown"); setTimeout(() => setResendStatus("idle"), RESEND_COOLDOWN_MS); } const resendLabel = resendStatus === "resending" ? "Sending…" : resendStatus === "cooldown" ? "Code sent — wait a moment" : "Resend code"; return (
handleChange(e.target.value)} placeholder="••••••" className="h-12 text-center text-2xl tracking-[0.5em] font-mono" disabled={verifyStatus === "verifying"} autoFocus />
{error &&

{error}

} {resendNotice && !error && (

{resendNotice}

)}
); }