import type {
  ChangeEvent,
  FocusEvent,
} from 'react'
import { useState } from 'react'

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

export const useAuthFields = (page: 'login'|'registration') => {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState('')

  const checkPassword = (pass: string) => {
    const regexp = /^(?=[^.,'"-])[\w\d@$!%*#?&;*]{8,}$/g
    return regexp.test(pass)
  }

  const onEmailChange = ({ target: { value } }: ChangeEvent<HTMLInputElement>) => {
    setError('')
    setEmail(value)
  }

  const onPasswordChange = ({ target: { value } }: ChangeEvent<HTMLInputElement>) => {
    setError('')
    setPassword(value)
    const isRegisterPage = page === 'registration'
    if (!checkPassword(value) && isRegisterPage) {
      setError('check_password')
    }
  }

  const onEmailBlur = ({ target: { value } }: FocusEvent<HTMLInputElement>) => {
    if (!value) {
      setError('error_empty_email')
    } else if (!isValidEmail(value)) {
      setError('error_invalid_email_format')
    }
  }

  const onPasswordBlur = ({ target: { value } }: FocusEvent<HTMLInputElement>) => {
    if (!value) {
      setError('error_empty_password')
    } else if (!isValidPassword(value)) {
      setError('error_simple_password')
    }
  }

  return {
    checkPassword,
    email,
    error,
    onEmailBlur,
    onEmailChange,
    onPasswordBlur,
    onPasswordChange,
    password,
  }
}
