import * as React from "react";
import { Field, OtpInput } from "@/components/ui/otp-input-verification";
import { ShieldCheck } from "lucide-react";
/* Two-step verification. The code submits itself when the last digit
lands, so there is no Verify button to find. The right code is 123456;
anything else marks the boxes invalid and says what to do. Resend waits
30 seconds, counting down. */
const wait = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
export default function OtpDemo() {
const [code, setCode] = React.useState("");
const [state, setState] = React.useState<"idle" | "checking" | "wrong" | "ok">("idle");
const [cooldown, setCooldown] = React.useState(30);
React.useEffect(() => {
if (cooldown <= 0) return;
const t = setTimeout(() => setCooldown((c) => c - 1), 1000);
return () => clearTimeout(t);
}, [cooldown]);
return (
<div className="flex min-h-screen w-full items-center justify-center bg-background p-6">
<div className="w-full max-w-[380px] min-w-0 rounded-[18px] [corner-shape:squircle] bg-card p-6 text-center ring-1 ring-border">
<span className="mx-auto grid size-11 place-items-center rounded-full bg-muted">
<ShieldCheck className="size-5" aria-hidden />
</span>
<h2 className="mt-3 text-[16px] font-semibold tracking-[-0.01em]">Enter the 6-digit code</h2>
<p className="mt-1 text-[13px] text-muted-foreground">We texted it to the phone ending in 42. Try 123456.</p>
<div className="mt-5 text-left">
<Field
label="Verification code"
hint={state === "ok" ? "Verified. Signing you in…" : state === "checking" ? "Checking…" : undefined}
error={state === "wrong" ? "That code is not right. Check the latest message." : undefined}
>
<OtpInput
value={code}
disabled={state === "checking" || state === "ok"}
onChange={(v) => {
setCode(v);
if (state === "wrong") setState("idle");
}}
onComplete={async (c) => {
setState("checking");
await wait(700);
setState(c === "123456" ? "ok" : "wrong");
}}
className="mx-auto"
/>
</Field>
</div>
<button
type="button"
disabled={cooldown > 0}
onClick={() => (setCooldown(30), setCode(""), setState("idle"))}
className="mt-5 text-[13px] font-medium underline-offset-4 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring disabled:text-muted-foreground disabled:no-underline"
>
{cooldown > 0 ? `Resend in ${cooldown}s` : "Send a new code"}
</button>
</div>
</div>
);
}