'use client' import type { InitValidateStatusResponse } from '@/models/common' import { zodResolver } from '@hookform/resolvers/zod' import { useRouter } from 'next/navigation' import * as React from 'react' import { useEffect, useState } from 'react' import { useForm } from 'react-hook-form' import { useTranslation } from 'react-i18next' import { z } from 'zod' import Button from '@/app/components/base/button' import { fetchInitValidateStatus, fetchSetupStatus, sendForgotPasswordEmail, } from '@/service/common' import { basePath } from '@/utils/var' import Input from '../components/base/input' import Loading from '../components/base/loading' const accountFormSchema = z.object({ email: z .string() .min(1, { message: 'error.emailInValid' }) .email('error.emailInValid'), }) type AccountFormValues = z.infer const ForgotPasswordForm = () => { const { t } = useTranslation() const router = useRouter() const [loading, setLoading] = useState(true) const [isEmailSent, setIsEmailSent] = useState(false) const { register, trigger, getValues, formState: { errors } } = useForm({ resolver: zodResolver(accountFormSchema), defaultValues: { email: '' }, }) const handleSendResetPasswordEmail = async (email: string) => { try { const res = await sendForgotPasswordEmail({ url: '/forgot-password', body: { email }, }) if (res.result === 'success') setIsEmailSent(true) else console.error('Email verification failed') } catch (error) { console.error('Request failed:', error) } } const handleSendResetPasswordClick = async () => { if (isEmailSent) { router.push('/signin') } else { const isValid = await trigger('email') if (isValid) { const email = getValues('email') await handleSendResetPasswordEmail(email) } } } useEffect(() => { fetchSetupStatus().then(() => { fetchInitValidateStatus().then((res: InitValidateStatusResponse) => { if (res.status === 'not_started') window.location.href = `${basePath}/init` }) setLoading(false) }) }, []) return ( loading ? : ( <>

{isEmailSent ? t('resetLinkSent', { ns: 'login' }) : t('forgotPassword', { ns: 'login' })}

{isEmailSent ? t('checkEmailForResetLink', { ns: 'login' }) : t('forgotPasswordDesc', { ns: 'login' })}

{!isEmailSent && (
{errors.email && {t(`${errors.email?.message}` as 'error.emailInValid', { ns: 'login' })}}
)}
) ) } export default ForgotPasswordForm