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 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 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,
    handleSubmit,
    isFetching,
    isSubmitDisabled,
    onEmailBlur,
    onEmailChange,
    onPasswordBlur,
    onPasswordChange,
    password,
    url: addLanguageUrlParam(lang, url),
  }
}
