import { useState, useEffect } from 'react' import { Button, FormControl, FormHelperText, TextField, Typography, Box} from '@mui/material' import { trpc } from '@/utils/trpc' import { toast } from 'react-toastify' import { TRPCErrorResponse } from '@trpc/server/rpc' const ChangePasswordForm = () => { const [password, setPassword] = useState('') const [password1, setPassword1] = useState('') const [password2, setPassword2] = useState('') const [passwordsMatch, setPasswordsMatch] = useState(false) const [disableSubmit, setDisableSubmit] = useState(true) const [tip, setTip] = useState('') const { mutateAsync: changeUserPassword } = trpc.auth.changePassword.useMutation() useEffect(() => { if (password1 == password) { setTip('New password cannot be the same as the old password') setDisableSubmit(true) } else if (password1 === '' || password2 === '' || password === '' ) { setDisableSubmit(true) setTip('Please fill out all fields') } else if (password1 === password2) { console.log('passwords match') setDisableSubmit(false) setPasswordsMatch(true) } else { console.log('passwords do not match') setPasswordsMatch(false) } }, [password1, password2, password]) const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); try { const changeResponse = await changeUserPassword({oldPassword: password, newPassword: password1}) if (changeResponse.success) { setPassword('') setPassword1('') setPassword2('') toast.success('Password changed successfully') } } catch (error) { if (error instanceof Error) { toast.error(error.message) } else { toast.error('An unknown error occurred') } } } return ( <FormControl component={'form'} sx={{ maxWidth: '500px' }} onSubmit={handleSubmit} > <Typography variant='h3'>Change Password</Typography> <TextField onChange={(e) => setPassword(e.target.value)} label='Current Password' value={password} type='password' /> <TextField onChange={(e) => setPassword1(e.target.value)} label='New Password' value={password1} type='password' /> <TextField onChange={(e) => setPassword2(e.target.value)} label='Confirm Password' value={password2} type='password' /> <FormHelperText sx={{ mb: '1px'}} error hidden={!disableSubmit}> {tip} </FormHelperText> <Button disabled={disableSubmit} variant='contained' type='submit' > Change Password </Button> </FormControl> ) } export default ChangePasswordForm