'use client' import { useCallback, useState } from 'react' import { useTranslation } from 'react-i18next' import useSWR from 'swr' import { useSearchParams } from 'next/navigation' import cn from 'classnames' import { CheckCircleIcon } from '@heroicons/react/24/solid' import Input from '../components/base/input' import Button from '@/app/components/base/button' import { changePasswordWithToken, verifyForgotPasswordToken } from '@/service/common' import Toast from '@/app/components/base/toast' import Loading from '@/app/components/base/loading' const validPassword = /^(?=.*[a-zA-Z])(?=.*\d).{8,}$/ const ChangePasswordForm = () => { const { t } = useTranslation() const searchParams = useSearchParams() const token = searchParams.get('token') const verifyTokenParams = { url: '/forgot-password/validity', body: { token }, } const { data: verifyTokenRes, mutate: revalidateToken } = useSWR(verifyTokenParams, verifyForgotPasswordToken, { revalidateOnFocus: false, }) const [password, setPassword] = useState('') const [confirmPassword, setConfirmPassword] = useState('') const [showSuccess, setShowSuccess] = useState(false) const showErrorMessage = useCallback((message: string) => { Toast.notify({ type: 'error', message, }) }, []) const valid = useCallback(() => { if (!password.trim()) { showErrorMessage(t('login.error.passwordEmpty')) return false } if (!validPassword.test(password)) { showErrorMessage(t('login.error.passwordInvalid')) return false } if (password !== confirmPassword) { showErrorMessage(t('common.account.notEqual')) return false } return true }, [password, confirmPassword, showErrorMessage, t]) const handleChangePassword = useCallback(async () => { const token = searchParams.get('token') || '' if (!valid()) return try { await changePasswordWithToken({ url: '/forgot-password/resets', body: { token, new_password: password, password_confirm: confirmPassword, }, }) setShowSuccess(true) } catch { await revalidateToken() } }, [password, revalidateToken, token, valid]) return (
{t('login.changePasswordTip')}