import {
  ChangeEvent,
  SyntheticEvent,
  useState,
} from 'react'

import { useHistory } from 'react-router'

import { useAuthFields } from 'features/AuthServiceApp/hooks/useAuthFields'
import { changePassword } from 'features/AuthServiceApp/requests/changePassword'
import { clients } from 'features/AuthServiceApp/config/clients'

import { useParamsUrl } from '../../hooks/useParamsUrl'

export const useChangePasswordForm = () => {
  const { client_id, redirect_uri } = useParamsUrl()
  const history = useHistory()

  const [error, setError] = useState('')
  const [modalOpen, setModalOpen] = useState<boolean>(false)
  const [isFetching, setIsFetching] = useState(false)
  const [password, setPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')
  const [disabled, setDisabled] = useState(true)

  const { checkPassword } = useAuthFields('login')

  const handleSubmit = async (event: SyntheticEvent) => {
    event?.preventDefault()
    setIsFetching(true)
    try {
      await changePassword(client_id, password)
      setError('')
      setIsFetching(false)
      setModalOpen(true)
    } catch (err) {
      setError(String(err))
      setIsFetching(false)
    }
  }
  const host = String(redirect_uri || clients[client_id].host)

  const redirectUrl = `/authorize?client_id=${client_id}&redirect_uri=${encodeURIComponent(host)}`

  const modalButtonClick = () => {
    history.push(redirectUrl)
  }

  const onPasswordChange = ({
    target: { value },
  }: ChangeEvent<HTMLInputElement>) => {
    if (!checkPassword(value)) {
      setError('check_password')
    } else {
      setDisabled(false)
      setError('')
    }
    setPassword(value)
  }

  const onConfirmPasswordChange = ({
    target: { value },
  }: ChangeEvent<HTMLInputElement>) => {
    setConfirmPassword(value)

    if (isMatchPasswords(password, value)) {
      setError('')
    } else {
      setError('error_passwords_missmatch')
    }
    if (!checkPassword(password)) setError('check_password')
  }

  const isMatchPasswords = (pass1: string, pass2: string) => pass1 === pass2

  const isSubmitDisabled = !password
  || !confirmPassword
  || !isMatchPasswords(password, confirmPassword)
  || Boolean(error)
  || isFetching

  return {
    confirmPassword,
    disabled,
    error,
    handleSubmit,
    isFetching,
    isSubmitDisabled,
    modalButtonClick,
    modalOpen,
    onConfirmPasswordChange,
    onPasswordChange,
    password,
  }
}
