import { SyntheticEvent, useState } from 'react'
import { useHistory } from 'react-router'

import { setAgreements } from 'requests/getAgreements'
import { useAuthFields } from 'features/AuthServiceApp/hooks/useAuthFields'

import { registerCheck } from '../../requests/register'
import { useParamsUrl } from '../../hooks/useParamsUrl'
import { PAGES } from '../../config/pages'

export const useRegistrationForm = () => {
  const history = useHistory()
  const urlParams = useParamsUrl()
  const [authError, setAuthError] = useState('')
  const [termsAccepted, setTermsAccepted] = useState(true)
  const [cookiesAccepted, setCookiesAccepted] = useState(true)
  const [isFetching, setIsFetching] = useState(false)
  const [isModalOpen, setIsModalOpen] = useState(false)
  const {
    email,
    error: formError,
    onEmailBlur,
    onEmailChange,
    onPasswordBlur,
    onPasswordChange,
    password,
  } = useAuthFields('registration')

  const isSubmitDisabled = (
    !email
    || !password
    || !termsAccepted
    || !cookiesAccepted
    || Boolean(formError)
    || isFetching
  )

  const handleSubmit = async (event: SyntheticEvent) => {
    event?.preventDefault()
    setIsFetching(true)
    try {
      await registerCheck({
        email,
        password,
        urlParams,
      })
      setAuthError('')
      setIsFetching(false)
      setIsModalOpen(true)
      setAgreements(email)
    } catch (err) {
      setAuthError(String(err))
      setIsFetching(false)
    }
  }

  const handleModalClose = () => {
    setIsModalOpen(false)
    history.replace(PAGES.login)
  }

  const onTermsChange = () => {
    setTermsAccepted(!termsAccepted)
  }

  const onCookiesChange = () => {
    setAuthError('')
    setCookiesAccepted(!cookiesAccepted)
    if (cookiesAccepted) {
      setAuthError('error_accept_cookies')
    }
  }

  return {
    authError,
    cookiesAccepted,
    email,
    formError,
    handleModalClose,
    handleSubmit,
    isFetching,
    isModalOpen,
    isSubmitDisabled,
    onCookiesChange,
    onEmailBlur,
    onEmailChange,
    onPasswordBlur,
    onPasswordChange,
    onTermsChange,
    password,
    termsAccepted,
  }
}
