import { SyntheticEvent, useState } from 'react'

import { useAuthFields } from 'features/AuthServiceApp/hooks/useAuthFields'

import { registerCheck } from '../../requests/register'

export const useRegistrationForm = () => {
  const [authError, setAuthError] = useState('')
  const [termsAccepted, setTermsAccepted] = useState(false)
  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
    || Boolean(formError)
    || isFetching
  )

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

  const handleModalClose = () => {
    setIsModalOpen(false)
  }

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

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