'use client'

import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { Link } from '@/i18n/navigation'

const ERROR_KEYS = ['cooldown', 'noEmail'] as const

/** Formatea una fecha ISO como "HH:MM:SS DD-MM-YYYY" (igual que el diseño original). */
function formatDate(iso: string): string {
  const d = new Date(iso)
  const p = (n: number) => String(n).padStart(2, '0')
  return `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())} ${p(d.getDate())}-${p(d.getMonth() + 1)}-${d.getFullYear()}`
}

export function SecurityTokenForm({ initialDate }: { initialDate: string | null }) {
  const t = useTranslations('SecurityToken')
  const [date, setDate] = useState(initialDate)
  const [busy, setBusy] = useState(false)
  const [sent, setSent] = useState(false)
  const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)

  async function request(e: React.FormEvent) {
    e.preventDefault()
    if (busy || sent) return
    setBusy(true)
    setMessage(null)
    try {
      const res = await fetch('/api/account/security-token', { method: 'POST', credentials: 'same-origin' })
      const data: { success?: boolean; error?: string; tokenDate?: string } = await res.json()
      if (data.success) {
        setMessage({ ok: true, text: t('success') })
        setSent(true)
        if (data.tokenDate) setDate(data.tokenDate)
      } else {
        const key = (ERROR_KEYS as readonly string[]).includes(data.error ?? '') ? data.error! : 'genericError'
        setMessage({ ok: false, text: t(key) })
        // Como el original: el mensaje de error desaparece tras 5 s.
        setTimeout(() => setMessage(null), 5000)
      }
    } catch {
      setMessage({ ok: false, text: t('genericError') })
      setTimeout(() => setMessage(null), 5000)
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="centered">
      <br />
      <br />
      <p>{t('requestDateLabel')}</p>
      <p><span className="yellow-info">{date ? formatDate(date) : t('never')}</span></p>
      <br />
      <form id="ns-sec-token-form" onSubmit={request} acceptCharset="utf-8">
        <button
          className="sec-token-button"
          type="submit"
          disabled={busy || sent}
          style={sent ? { color: '#d79602' } : undefined}
        >
          {sent ? t('sent') : busy ? t('requesting') : t('request')}
        </button>
      </form>
      <br />
      <hr />
      <div className="alert-message" id="sec-token-response" style={{ display: message ? 'block' : 'none' }}>
        {message && <span className={message.ok ? 'ok-form-response' : 'red-form-response'}>{message.text}</span>}
      </div>
      <br />
      <p><Link href="/recover">{t('forgot')}</Link></p>
      <br />
    </div>
  )
}
