import { useState } from 'react'

interface Props {
  valid: boolean
  token: string
  resetUrl: string
  recoverUrl: string
  csrfToken: string
}

export function ResetPassword({ valid, token, resetUrl, recoverUrl, csrfToken }: Props) {
  const [password, setPassword] = useState('')
  const [confPassword, setConfPassword] = useState('')
  const [showPw, setShowPw] = useState(false)
  const [busy, setBusy] = useState(false)
  const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)
  const [done, setDone] = useState(false)

  if (!valid) {
    return (
      <div className="body-box-content centered">
        <p className="red-form-response">El enlace no es válido o ha caducado.</p>
        <br />
        <p>
          Puedes solicitar uno nuevo en <a href={recoverUrl}>recuperar cuenta</a>.
        </p>
      </div>
    )
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (busy || done) return
    if (password.trim() === '' || password.trim() !== confPassword.trim()) {
      setMessage({ ok: false, text: 'Las contraseñas no coinciden.' })
      return
    }
    setBusy(true)
    setMessage(null)

    const body = new URLSearchParams()
    body.set('token', token)
    body.set('new-password', password.trim())
    body.set('conf-password', confPassword.trim())
    body.set('csrfmiddlewaretoken', csrfToken)

    try {
      const resp = await fetch(resetUrl, {
        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: { success?: boolean; message?: string; redirect?: string } = await resp.json()
      setMessage({ ok: !!data.success, text: data.message || '' })
      if (data.success) {
        setDone(true)
        if (data.redirect) {
          setTimeout(() => {
            window.location.href = data.redirect as string
          }, 2500)
        }
      } else {
        setBusy(false)
      }
    } catch {
      setMessage({ ok: false, text: 'Error en el servidor. Inténtalo de nuevo más tarde.' })
      setBusy(false)
    }
  }

  return (
    <div className="body-box-content centered">
      <form id="nw-reset-form" onSubmit={handleSubmit} acceptCharset="utf-8">
        <table className="middle-center-table">
          <tbody>
            <tr>
              <td>
                <input
                  type={showPw ? 'text' : 'password'}
                  maxLength={16}
                  name="new-password"
                  id="new-password"
                  placeholder="Nueva contraseña"
                  autoFocus
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                />
                <span
                  className={`far toggle-password ${showPw ? 'fa-eye-slash' : 'fa-eye'}`}
                  onClick={() => setShowPw((v) => !v)}
                />
              </td>
            </tr>
            <tr>
              <td>
                <input
                  type={showPw ? 'text' : 'password'}
                  maxLength={16}
                  name="conf-password"
                  id="conf-password"
                  placeholder="Confirmar contraseña"
                  value={confPassword}
                  onChange={(e) => setConfPassword(e.target.value)}
                />
              </td>
            </tr>
            <tr>
              <td>
                <button type="submit" className="login-button" disabled={busy || done}>
                  {done ? 'Hecho' : busy ? 'Guardando…' : 'Restablecer contraseña'}
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </form>
      <hr />
      <div className="alert-message" style={{ display: message ? 'block' : 'none' }}>
        {message && (
          <span className={message.ok ? 'ok-form-response' : 'red-form-response'}>{message.text}</span>
        )}
      </div>
    </div>
  )
}
