import Pristine from 'pristinejs'
import { useEffect, useState } from 'react'
import { UserIcon, EyeIcon, EyeSlashIcon, KeyIcon } from '@heroicons/react/24/solid'
import functions from 'v-functions'
import useI18n from '@/hooks/useI18n'
import presets from '@/utils/globalPresets'
import useHasMounted from '@/hooks/useHasMounted'

let validateLogin = null

const FormLogin = ({ onLogin }) => {
  const i18n = useI18n()
  const hasMounted = useHasMounted()
  const [viewPassword, setViewPassword] = useState(false)
  const [isInputValid, setIsInputValid] = useState(false)

  const validate = (event) => {
    if (event) {
      event.preventDefault()
      event.stopPropagation()
    }
    if (validateLogin && validateLogin !== null) {
      const resulValidate = validateLogin.validate()
      setIsInputValid(resulValidate)
    }
  }

  const doLogin = (event) => {
    if (event) {
      event.preventDefault()
      event.stopPropagation()
    }
    if (isInputValid === true) {
      const emailLogin = document.getElementById('usuario')
      const passwordLogin = document.getElementById('clave')
      const datos = {
        email: functions.toUpperCaseAndTrim(emailLogin.value),
        password: functions.trim(passwordLogin.value)
      }
      setIsInputValid(false) // para prevenir doble click
      onLogin(datos)
    }
  }

  // when page is mounted
  useEffect(() => {
    if (hasMounted) {
      const helem = document.getElementById('frmLogin')
      validateLogin = new Pristine(helem, presets.pristine, false)
      const helemUsuario = document.getElementById('usuario')
      helemUsuario.focus()
    }
  }, [hasMounted])

  useEffect(() => {
    const handleKeyDown = (event) => {
      if (event.key === 'Enter') {
        validate(event)
        if (isInputValid === true) {
          doLogin(event)
          event.preventDefault()
          event.stopPropagation()
        }
      }
    }

    document.addEventListener('keydown', handleKeyDown)
    return () => {
      document.removeEventListener('keydown', handleKeyDown)
    }
  })

  return (
    <form id="frmLogin" name="frmLogin" method="post" onSubmit={(event) => doLogin(event)} noValidate >
      <div className="flex w-full flex-col space-y-4 px-4 ">
        <div className="form-group  flex flex-col">
          <div className="via-label">
            { i18n.t('login.user') }
            <div className="inline-flex font-semibold text-red-500">(*)</div>
          </div>
          <div className="relative w-full">
            <input
              id="usuario"
              name="usuario"
              required
              placeholder=" "
              type="email"
              data-pristine-required-message={i18n.t('login.validacion_correo')}
              className={'via-input'}
              onChange={(e) => { validate(e) }}
            />
            <button
              className={'via-append-input'}
              onClick={(e) => { e.stopPropagation() }}
              disabled
            >
              <UserIcon className="h-5 w-5" />
            </button>
          </div>
        </div>
        <div className="form-group  flex flex-col">
          <div className={'via-label'}>
            { i18n.t('login.password') }
            <div className="inline-flex font-semibold text-red-500">(*)</div>
          </div>
          <div className="relative w-full">
            <input
              id="clave"
              name="clave"
              required
              placeholder=" "
              type={viewPassword === false ? 'password' : 'text'}
              data-pristine-required-message={i18n.t('login.validacion_password')}
              className={'via-input'}
              onChange={(e) => { validate(e) }}
            />
            <button
              className={'via-append-input'}
              onClick={(e) => { e.stopPropagation(); e.preventDefault(); setViewPassword(!viewPassword) }}
            >
              { viewPassword === false && <EyeIcon className="h-5 w-5" /> }
              { viewPassword === true && <EyeSlashIcon className="h-5 w-5" /> }
            </button>
          </div>
        </div>
        <div className={'via-div-actions'}>
          <button
            type="submit"
            disabled={!isInputValid}
            className={`${'via-button'} ${(isInputValid ? 'bg-cyan-900' : 'bg-red-400')} mx-0 w-full justify-center`}
          >
            <KeyIcon className="h-5 w-5 pr-2" />
            { i18n.t('login.connect') }
          </button>
        </div>
      </div>
    </form>
  )
}

export default FormLogin
