"use client"; import React, { useRef, useState } from "react"; import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; import { login } from "./action"; import { LoginFormSchema } from "@/types/schemas/authentication.schema"; import toast from "react-hot-toast"; import HCaptcha from "@hcaptcha/react-hcaptcha"; export function LoginForm() { const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [errors, setErrors] = useState<{ email?: string; password?: string; server?: string }>({}); const [captchaToken, setCaptchaToken] = useState(undefined); const captcha = useRef(null); const handleSubmit = async (event: React.FormEvent) => { event.preventDefault(); const formData = { email, password, options: { captchaToken } }; const result = LoginFormSchema.safeParse(formData); if (!result.success) { const formErrors: { email?: string; password?: string } = {}; result.error.errors.forEach((error) => { formErrors[error.path[0] as keyof typeof formErrors] = error.message; }); setErrors(formErrors); return; } setErrors({}); const form = new FormData(); form.set("email", email); form.set("password", password); if (captchaToken) { form.set("captchaToken", captchaToken); } try { await login(form); captcha.current?.resetCaptcha(); toast.success("Login succesfully!"); } catch (authError: any) { captcha.current?.resetCaptcha(); setErrors((prevErrors) => ({ ...prevErrors, server: authError.message || "An error occurred during login.", })); } }; return (
setEmail(e.target.value)} placeholder="Email" /> {errors.email &&

{errors.email}

}
setPassword(e.target.value)} placeholder="Password" /> {errors.password &&

{errors.password}

}
{ setCaptchaToken(token); }} /> {errors.server &&

{errors.server}

} ); }