import { useState } from 'react'
import { useTurnstile } from '../turnstile'

interface Props {
  loginUrl: string
  successUrl: string
  csrfToken: string
  siteKey: string
}

type LoginResponse = {
  success?: boolean
  alert?: boolean
  locked?: boolean
  error?: string
}

export function LoginForm({ loginUrl, successUrl, csrfToken, siteKey }: Props) {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [showPassword, setShowPassword] = useState(false)
  const [buttonText, setButtonText] = useState('Conectar')
  const [busy, setBusy] = useState(false)
  const [message, setMessage] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null)
  const { ref: turnstileRef, token: captchaToken } = useTurnstile(siteKey)

  function transientError(text: string) {
    setMessage({ kind: 'err', text })
    setBusy(false)
    setButtonText('Conectar')
    setTimeout(() => setMessage(null), 5000)
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (busy) return

    if (email.trim() === '' || password.trim() === '') {
      transientError('Por favor rellene todos los campos.')
      return
    }

    setBusy(true)
    setButtonText('Conectando')
    setMessage(null)

    const body = new URLSearchParams()
    body.set('email', email.trim())
    body.set('password', password.trim())
    body.set('csrfmiddlewaretoken', csrfToken)
    body.set('cf-turnstile-response', captchaToken)

    try {
      const resp = await fetch(loginUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'X-CSRFToken': csrfToken,
          Accept: 'application/json',
        },
        credentials: 'same-origin',
        body: body.toString(),
      })
      if (!resp.ok) throw new Error(`HTTP ${resp.status}`)
      const data: LoginResponse = await resp.json()

      if (data.success === true) {
        setButtonText('Conectado')
        setMessage({ kind: 'ok', text: 'Conexión exitosa. Redirigiendo…' })
        setTimeout(() => {
          window.location.href = successUrl
        }, 3000)
      } else if (data.alert === true) {
        setButtonText('Sancionado')
        setBusy(false)
      } else if (data.locked === true) {
        setButtonText('Seguridad')
        setBusy(false)
      } else {
        transientError(data.error || 'Nombre de usuario / Contraseña incorrectos.')
      }
    } catch {
      setTimeout(() => {
        alert('Algo ha salido mal. Por favor intente más tarde')
        window.location.reload()
      }, 2000)
    }
  }

  return (
    <>
      <form id="nw-login-form" onSubmit={handleSubmit} acceptCharset="utf-8">
        <table className="middle-center-table">
          <tbody>
            <tr>
              <td>
                <input
                  type="email"
                  maxLength={320}
                  name="email"
                  id="username"
                  placeholder="Correo electrónico"
                  autoFocus
                  required
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                />
              </td>
            </tr>
            <tr>
              <td>
                <input
                  type={showPassword ? 'text' : 'password'}
                  maxLength={16}
                  name="password"
                  id="password"
                  placeholder="Contraseña"
                  required
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                />
                <span
                  className={`far toggle-password ${showPassword ? 'fa-eye-slash' : 'fa-eye'}`}
                  onClick={() => setShowPassword((v) => !v)}
                />
              </td>
            </tr>
            <tr>
              <td>
                <div ref={turnstileRef} className="cf-turnstile" style={{ display: 'inline-block' }} />
              </td>
            </tr>
            <tr>
              <td>
                <button
                  type="submit"
                  className="login-button"
                  id="login-button"
                  disabled={busy || (!!siteKey && !captchaToken)}
                >
                  {buttonText}
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </form>
      <hr />
      <div className="alert-message" id="login-response">
        {message && (
          <span className={message.kind === 'ok' ? 'ok-form-response' : 'red-form-response'}>
            {message.text}
          </span>
        )}
      </div>
    </>
  )
}
