import { ChangeEvent, useState } from 'react'

import { isValidEmail } from 'features/AuthServiceApp/helpers/isValidEmail'
import { loginCheckChangePass } from 'features/AuthServiceApp/requests/loginCheck'

export const useRecovery = (setIsModalOpen: (value: boolean) => void) => {
  const [isSendBtnDisabled, setIsSendBtnDisabled] = useState(true)
  const [error, setError] = useState('')
  const [email, setEmail] = useState('')
  const [isFetching, setIsFetching] = useState(false)
  const [isSendMessage, setIsSendMessage] = useState(false)

  const onEmailChange = ({
    target: { value },
  }: ChangeEvent<HTMLInputElement>) => {
    setError('')
    setEmail(value)
    if (isValidEmail(value)) {
      setIsSendBtnDisabled(false)
    } else {
      setIsSendBtnDisabled(true)
    }
  }

  const closePopup = () => {
    setIsSendMessage(false)
    setIsFetching(false)
    setError('')
    setEmail('')
    setIsSendBtnDisabled(true)
    setIsModalOpen(false)
  }

  const handleError = (err: string) => {
    setError(err)
    setIsFetching(false)
  }

  const handleSubmit = () => {
    if (isSendMessage && !isFetching) {
      closePopup()
    } else {
      setIsFetching(true)
      loginCheckChangePass(email)
        .then(() => setIsSendMessage(true))
        .then(() => setIsFetching(false))
        .catch(handleError)
    }
  }

  return {
    closePopup,
    email,
    error,
    handleSubmit,
    isFetching,
    isSendBtnDisabled,
    isSendMessage,
    // onEmailBlur,
    onEmailChange,
  }
}
