import { useState } from 'react'

interface Props {
  url: string
  csrfToken: string
  loginUrl: string
}

interface Field {
  key: 'cur' | 'new' | 'conf' | 'token'
  name: string
  placeholder: string
  maxLength: number
}

const FIELDS: Field[] = [
  { key: 'cur', name: 'cur-password', placeholder: 'Contraseña actual', maxLength: 16 },
  { key: 'new', name: 'new-password', placeholder: 'Contraseña nueva', maxLength: 16 },
  { key: 'conf', name: 'conf-new-password', placeholder: 'Confirmar contraseña nueva', maxLength: 16 },
  { key: 'token', name: 'security-token', placeholder: 'Token de seguridad', maxLength: 6 },
]

export function ChangePasswordForm({ url, csrfToken, loginUrl }: Props) {
  const [values, setValues] = useState<Record<string, string>>({})
  const [shown, setShown] = useState<Record<string, boolean>>({})
  const [busy, setBusy] = useState(false)
  const [done, setDone] = useState(false)
  const [message, setMessage] = useState<{ ok: boolean; html: string } | null>(null)

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (busy || done) return
    setBusy(true)
    setMessage(null)

    const body = new URLSearchParams()
    for (const f of FIELDS) body.set(f.name, (values[f.key] || '').trim())
    body.set('csrfmiddlewaretoken', csrfToken)

    try {
      const resp = await fetch(url, {
        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?: boolean } = await resp.json()
      setMessage({ ok: !!data.success, html: data.message || '' })
      if (data.success && data.redirect) {
        setDone(true)
        setTimeout(() => {
          window.location.href = loginUrl
        }, 3000)
      } else {
        setBusy(false)
      }
    } catch {
      setMessage({ ok: false, html: '<span class="red-form-response">Error en el servidor. Inténtalo más tarde.</span>' })
      setBusy(false)
    }
  }

  return (
    <>
      <form id="nw-change-password-form" onSubmit={handleSubmit} acceptCharset="utf-8">
        <table className="middle-center-table">
          <tbody>
            {FIELDS.map((f) => (
              <tr key={f.key}>
                <td>
                  <input
                    type={shown[f.key] ? 'text' : 'password'}
                    maxLength={f.maxLength}
                    name={f.name}
                    id={f.name}
                    placeholder={f.placeholder}
                    value={values[f.key] || ''}
                    onChange={(e) => setValues((v) => ({ ...v, [f.key]: e.target.value }))}
                  />
                  <span
                    className={`far toggle-password ${shown[f.key] ? 'fa-eye-slash' : 'fa-eye'}`}
                    onClick={() => setShown((s) => ({ ...s, [f.key]: !s[f.key] }))}
                  />
                </td>
              </tr>
            ))}
            <tr>
              <td>
                <button type="submit" className="change-password-button" disabled={busy || done}>
                  {done ? 'Hecho' : busy ? 'Cambiando…' : 'Cambiar contraseña'}
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </form>
      <hr />
      <div className="alert-message" id="change-password-response" style={{ display: message ? 'block' : 'none' }}>
        {message && <span dangerouslySetInnerHTML={{ __html: message.html }} />}
      </div>
    </>
  )
}
