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

import { loginCheck } from 'features/AuthServiceApp/requests/authСheck'
import { getApiUrl } from 'features/AuthServiceApp/config/routes'
import { useLexicsStore } from 'features/LexicsStore'
import { useAuthFields } from 'features/AuthServiceApp/hooks/useAuthFields'
import { getClientSettings } from 'features/AuthStore/helpers'

import { useLocation } from 'react-router'

const url = getApiUrl('/authorize')

export const useLoginForm = () => {
  const location = useLocation()
  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 redirect_url = new URLSearchParams(location.search).get('redirect_uri')

  const {
    client_id,
    redirect_uri,
    response_mode,
    response_type,
    scope,
  } = getClientSettings()

  const currentRedirectUrl = redirect_url ?? redirect_uri

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

  const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    setIsFetching(true)
    try {
      await loginCheck(
        email,
        lang,
        password,
        currentRedirectUrl,
      )
      submitForm()
    } catch (err) {
      handleError(String(err))
    }
  }

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

  return {
    authError,
    client_id,
    email,
    formError,
    formRef,
    handleModalOpen,
    handleSubmit,
    isFetching,
    isModalOpen,
    isSubmitDisabled,
    lang,
    onEmailBlur,
    onEmailChange,
    onPasswordBlur,
    onPasswordChange,
    password,
    redirect_uri: currentRedirectUrl,
    response_mode,
    response_type,
    scope,
    setIsModalOpen,
    url,
  }
}
