import {
  useEffect,
  useRef,
  useState,
  useCallback,
  FormEvent,
  FocusEvent,
  ChangeEvent,
} from 'react'

import { isValidEmail } from 'features/AuthServiceApp/helpers/isValidEmail'

import { addAccessTokenToUrl } from 'helpers/languageUrlParam'

import { AUTH_SERVICE } from 'config'

export const useOauth = () => {
  const [email, setEmail] = useState('')
  const [error, setError] = useState('')
  const [errorAuth, setErrorAuth] = useState('')
  const [isOpenErrorPopup, setIsOpenErrorPopup] = useState(false)
  const [showEmailField, showShowEmailField] = useState(false)

  const formRef = useRef<HTMLFormElement>(null)

  const authorize = useCallback(async () => {
    if (!formRef.current) return

    const url = addAccessTokenToUrl(`${AUTH_SERVICE}/oauth`)

    const res = await fetch(url, {
      body: new FormData(formRef.current),
      method: 'POST',
    })

    if (res.ok && res.redirected) {
      formRef.current.submit()
    } else {
      const data = await res.json()

      if (data.error === 'Token missing email field') {
        showShowEmailField(true)
      }

      if (data.error === 'Email already exists') {
        setErrorAuth('error_email_already_exist')
        setIsOpenErrorPopup(true)
      }
    }
  }, [])

  const handleEmailChange = ({ target: { value } }: ChangeEvent<HTMLInputElement>) => {
    setEmail(value)
  }

  const handleEmailFocus = () => {
    setError('')
    setErrorAuth('')
  }

  const handleEmailBlur = ({ target: { value } }: FocusEvent<HTMLInputElement>) => {
    if (!isValidEmail(value) && value) {
      setError('error_invalid_email_format')
    }
  }

  const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault()

    if (error) return

    authorize()
  }

  useEffect(() => {
    authorize()
  }, [authorize])

  return {
    email,
    error,
    errorAuth,
    formRef,
    handleEmailBlur,
    handleEmailChange,
    handleEmailFocus,
    handleSubmit,
    isOpenErrorPopup,
    setIsOpenErrorPopup,
    showEmailField,
  }
}
