import { ChangeEvent, SyntheticEvent, useState, } from 'react' import { useHistory } from 'react-router' import { useAuthFields } from 'features/AuthServiceApp/hooks/useAuthFields' import { changePassword } from 'features/AuthServiceApp/requests/changePassword' import { useParamsUrl } from '../../hooks/useParamsUrl' export const useChangePasswordForm = () => { const { client_id } = useParamsUrl() const history = useHistory() const [error, setError] = useState('') const [isFetching, setIsFetching] = useState(false) const [password, setPassword] = useState('') const [confirmPassword, setConfirmPassword] = useState('') const [disabled, setDisabled] = useState(true) const { checkPassword } = useAuthFields('login') const handleSubmit = async (event: SyntheticEvent) => { event?.preventDefault() setIsFetching(true) try { await changePassword(client_id, password) setError('') setIsFetching(false) history.push(`/authorize?client_id=${client_id}`) } catch (err) { setError(String(err)) setIsFetching(false) } } const onPasswordChange = ({ target: { value }, }: ChangeEvent) => { if (!checkPassword(value)) { setError('check_password') } else { setDisabled(false) setError('') } setPassword(value) } const onConfirmPasswordChange = ({ target: { value }, }: ChangeEvent) => { setConfirmPassword(value) if (isMatchPasswords(password, value)) { setError('') } else { setError('error_passwords_missmatch') } } const isMatchPasswords = (pass1: string, pass2: string) => pass1 === pass2 const isSubmitDisabled = !password || !confirmPassword || !isMatchPasswords(password, confirmPassword) || Boolean(error) || isFetching return { confirmPassword, disabled, error, handleSubmit, isFetching, isSubmitDisabled, onConfirmPasswordChange, onPasswordChange, password, } }