"use client"; import * as React from "react"; import { useRouter, useSearchParams } from "next/navigation"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } from "react-hook-form"; import * as z from "zod"; import { IconLoader } from "@tabler/icons-react"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; import { Label } from "@/components/ui/label"; import { InputOTP, InputOTPGroup, InputOTPSlot, } from "@/components/ui/input-otp"; const codeSchema = z.object({ code: z.string().length(6, "Code must be 6 digits"), }); type CodeFormData = z.infer; export function VerifyEmailForm() { const router = useRouter(); const searchParams = useSearchParams(); const email = searchParams.get("email") || ""; const userId = searchParams.get("userId") || ""; const [isLoading, setIsLoading] = React.useState(false); const { watch, setValue, handleSubmit, formState: { errors }, } = useForm({ resolver: zodResolver(codeSchema), defaultValues: { code: "" }, }); const onSubmit = async (data: CodeFormData) => { setIsLoading(true); try { const response = await fetch("/api/auth/verify-email", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ code: data.code, userId, }), }); const result = (await response.json()) as { success: boolean; message?: string; error?: string; [key: string]: unknown; }; if (result.success) { toast.success(result.message); router.push("/login"); } else { toast.error(result.error || "Verification failed"); } } catch { toast.error("An error occurred. Please try again."); } finally { setIsLoading(false); } }; const handleCodeChange = (value: string) => { setValue("code", value); if (value.length === 6) { handleSubmit(onSubmit)(); } }; return (

We sent a verification code to{" "} {email || "your email"}

{errors.code && (

{errors.code.message}

)}
); }