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 [modalOpen, setModalOpen] = useState<boolean>(false)
  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)
      setModalOpen(true)
    } catch (err) {
      setError(String(err))
      setIsFetching(false)
    }
  }

  const modalButtonClick = () => {
    history.push(`/authorize?client_id=${client_id}`)
  }

  const onPasswordChange = ({
    target: { value },
  }: ChangeEvent<HTMLInputElement>) => {
    if (!checkPassword(value)) {
      setError('check_password')
    } else {
      setDisabled(false)
      setError('')
    }
    setPassword(value)
  }

  const onConfirmPasswordChange = ({
    target: { value },
  }: ChangeEvent<HTMLInputElement>) => {
    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,
    modalButtonClick,
    modalOpen,
    onConfirmPasswordChange,
    onPasswordChange,
    password,
  }
}
