"use client"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } from "react-hook-form"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { toast, Toaster } from "sonner"; import { z } from "zod"; import { Button } from "@/components/ui/button"; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { Input } from "@/components/ui/input"; const formSchema = z .object({ firstName: z .string() .min(2, { message: "First name must be at least 2 characters." }), lastName: z .string() .min(2, { message: "Last name must be at least 2 characters." }), email: z.string().email({ message: "Please enter a valid email address." }), password: z .string() .min(6, { message: "Password must be at least 6 characters." }), repeatPassword: z .string() .min(6, { message: "Repeat password must be at least 6 characters." }), }) .refine((data) => data.password === data.repeatPassword, { path: ["repeatPassword"], message: "Passwords do not match.", }); export function CreateAccountForm() { const router = useRouter(); const [isLoading, setIsLoading] = useState(false); const form = useForm({ resolver: zodResolver(formSchema), defaultValues: { firstName: "", lastName: "", email: "", password: "", repeatPassword: "", }, }); const onSubmit = async (data: z.infer) => { try { setIsLoading(true); const response = await fetch("/api/auth/register", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(data), }); const result = await response.json(); if (!response.ok) { toast.error(result.error || "Registration failed"); return; } // Show success message toast.success("Account Created", { duration: 2000, position: "top-center", }); // Redirect to login page setTimeout(() => { router.push("/login"); }, 1000); } catch (error) { console.error("Registration error:", error); toast.error("Registration failed"); } finally { setIsLoading(false); } }; return (
( First Name )} /> ( Last Name )} /> ( Email )} /> ( Password )} /> ( Repeat Password )} />
); }