import { useState } from 'react'

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

export function SecurityTokenForm({ url, csrfToken, initialDate }: Props) {
  const [date, setDate] = useState(initialDate)
  const [busy, setBusy] = useState(false)
  const [message, setMessage] = useState<{ ok: boolean; html: string } | null>(null)

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

    const body = new URLSearchParams()
    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; token_date?: string } = await resp.json()
      setMessage({ ok: !!data.success, html: data.message || '' })
      if (data.success && data.token_date) setDate(data.token_date)
    } catch {
      setMessage({ ok: false, html: '<span class="red-form-response">Error en el servidor. Inténtalo más tarde.</span>' })
    } finally {
      setBusy(false)
    }
  }

  return (
    <>
      <p>Fecha de solicitud de Token de seguridad:</p>
      <p><span id="token-date">{date}</span></p>
      <br />
      <form id="nw-sec-token-form" onSubmit={handleSubmit}>
        <button className="sec-token-button" type="submit" disabled={busy}>
          {busy ? 'Solicitando…' : 'Solicitar token'}
        </button>
      </form>
      <br />
      <hr />
      <div className="alert-message" id="sec-token-response" style={{ display: message ? 'block' : 'none' }}>
        {message && <span dangerouslySetInnerHTML={{ __html: message.html }} />}
      </div>
    </>
  )
}
