'use client' import { useCallback, useState } from 'react' import { useTranslation } from 'react-i18next' import { useRouter, useSearchParams } from 'next/navigation' import cn from 'classnames' import { RiCheckboxCircleFill } from '@remixicon/react' import { useCountDown } from 'ahooks' import Button from '@/app/components/base/button' import { changePasswordWithToken } from '@/service/common' import Toast from '@/app/components/base/toast' import Input from '@/app/components/base/input' const validPassword = /^(?=.*[a-zA-Z])(?=.*\d).{8,}$/ const ChangePasswordForm = () => { const { t } = useTranslation() const router = useRouter() const searchParams = useSearchParams() const token = decodeURIComponent(searchParams.get('token') || '') const [password, setPassword] = useState('') const [confirmPassword, setConfirmPassword] = useState('') const [showSuccess, setShowSuccess] = useState(false) const [showPassword, setShowPassword] = useState(false) const [showConfirmPassword, setShowConfirmPassword] = useState(false) const showErrorMessage = useCallback((message: string) => { Toast.notify({ type: 'error', message, }) }, []) const getSignInUrl = () => { if (searchParams.has('invite_token')) { const params = new URLSearchParams() params.set('token', searchParams.get('invite_token') as string) return `/activate?${params.toString()}` } return '/signin' } const AUTO_REDIRECT_TIME = 5000 const [leftTime, setLeftTime] = useState(undefined) const [countdown] = useCountDown({ leftTime, onEnd: () => { router.replace(getSignInUrl()) }, }) 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 () => { if (!valid()) return try { await changePasswordWithToken({ url: '/forgot-password/resets', body: { token, new_password: password, password_confirm: confirmPassword, }, }) setShowSuccess(true) setLeftTime(AUTO_REDIRECT_TIME) } catch (error) { console.error(error) } }, [password, token, valid, confirmPassword]) return (
{!showSuccess && (

{t('login.changePassword')}

{t('login.changePasswordTip')}

{/* Password */}
setPassword(e.target.value)} placeholder={t('login.passwordPlaceholder') || ''} />
{t('login.error.passwordInvalid')}
{/* Confirm Password */}
setConfirmPassword(e.target.value)} placeholder={t('login.confirmPasswordPlaceholder') || ''} />
)} {showSuccess && (

{t('login.passwordChangedTip')}

)}
) } export default ChangePasswordForm