import type { FormEvent } from 'react'
import {
  useRef,
  useState,
  useEffect,
} from 'react'

import { addLanguageUrlParam } from 'helpers/languageUrlParam'

import { loginCheck } from 'features/AuthServiceApp/requests/auth'
import { getApiUrl } from 'features/AuthServiceApp/config/routes'

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

const url = getApiUrl('/authorize')

export const useLoginForm = () => {
  const { lang } = useLexicsStore()
  const [authError, setAuthError] = useState('')
  const [isFetching, setIsFetching] = useState(false)
  const [isModalOpen, setIsModalOpen] = useState(false)

  const formRef = useRef<HTMLFormElement>(null)
  const {
    email,
    error: formError,
    onEmailBlur,
    onEmailChange,
    onPasswordBlur,
    onPasswordChange,
    password,
  } = useAuthFields('login')

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

  const handleModalOpen = () => {
    setIsModalOpen(true)
  }

  const submitForm = () => formRef.current?.submit()

  const handleError = (error: string) => {
    setAuthError(error)
    setIsFetching(false)
  }

  const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    setIsFetching(true)
    loginCheck(email, password)
      .then(submitForm)
      .catch(handleError)
  }

  useEffect(() => {
    setAuthError('')
  }, [email, password])

  return {
    authError,
    email,
    formError,
    formRef,
    handleModalOpen,
    handleSubmit,
    isFetching,
    isModalOpen,
    isSubmitDisabled,
    onEmailBlur,
    onEmailChange,
    onPasswordBlur,
    onPasswordChange,
    password,
    setIsModalOpen,
    url: addLanguageUrlParam(lang, url),
  }
}
