'use client'

import { useState } from 'react'
import { CharacterSelect, type CharOption } from '@/components/CharacterSelect'
import { Turnstile } from '@/components/Turnstile'

const ITEM_DB = 'https://wotlk.novawow.com'

interface DeletedItem {
  recoverId: number
  itemId: number
  name: string
  count: number
}

function itemsError(error?: string, minutes?: number): string {
  switch (error) {
    case 'characterNotOwned':
      return 'El personaje seleccionado no es válido.'
    case 'cooldown':
      return `Solo puedes consultar los ítems de este personaje cada 8 horas (faltan ${minutes ?? 0} min).`
    case 'soapError':
      return 'No se pudo conectar con el servidor de juego. Inténtalo más tarde.'
    case 'insufficientPoints':
      return 'No tienes suficientes PD (se requieren 100 por ítem).'
    case 'captcha':
      return 'Verifica que no eres un robot.'
    case 'notAuthenticated':
      return 'Tu sesión ha expirado. Inicia sesión de nuevo.'
    default:
      return 'Algo ha salido mal. Inténtalo de nuevo.'
  }
}

export function RestoreItemsForm({ characters, canAfford }: { characters: CharOption[]; canAfford: boolean }) {
  const [character, setCharacter] = useState('')
  const [captcha, setCaptcha] = useState('')
  const [captchaKey, setCaptchaKey] = useState(0)
  const [busy, setBusy] = useState(false)
  const [items, setItems] = useState<DeletedItem[] | null>(null)
  const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)

  if (!canAfford) {
    return (
      <div id="char-selection">
        <span>No tienes PD suficientes</span>
      </div>
    )
  }

  async function search(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    if (busy || !character) return
    setBusy(true)
    setMessage(null)
    try {
      const res = await fetch('/api/character/restore-items/search', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ character, turnstile: captcha }),
      })
      const data: { success?: boolean; error?: string; minutes?: number; items?: DeletedItem[] } = await res.json()
      if (data.success) {
        setItems(data.items ?? [])
        if ((data.items ?? []).length === 0) setMessage({ ok: true, text: 'Este personaje no tiene ítems borrados recuperables.' })
      } else {
        setMessage({ ok: false, text: itemsError(data.error, data.minutes) })
      }
    } catch {
      setMessage({ ok: false, text: itemsError() })
    } finally {
      setBusy(false)
      setCaptcha('')
      setCaptchaKey((k) => k + 1)
    }
  }

  async function restore(item: DeletedItem) {
    if (busy) return
    if (!window.confirm(`¿Recuperar "${item.name}" por 100 PD?`)) return
    setBusy(true)
    setMessage(null)
    try {
      const res = await fetch('/api/character/restore-items/restore', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ character, recoverId: item.recoverId }),
      })
      const data: { success?: boolean; error?: string } = await res.json()
      if (data.success) {
        setItems((prev) => (prev ? prev.filter((i) => i.recoverId !== item.recoverId) : prev))
        setMessage({ ok: true, text: `¡"${item.name}" recuperado! Se han descontado 100 PD.` })
      } else {
        setMessage({ ok: false, text: itemsError(data.error) })
      }
    } catch {
      setMessage({ ok: false, text: itemsError() })
    } finally {
      setBusy(false)
    }
  }

  function reset() {
    setItems(null)
    setMessage(null)
    setCharacter('')
    setCaptcha('')
    setCaptchaKey((k) => k + 1)
  }

  return (
    <div className="centered">
      {items === null ? (
        <div id="char-selection">
          <form id="uw-search-items-form" onSubmit={search} acceptCharset="utf-8">
            <CharacterSelect characters={characters} value={character} onChange={setCharacter} placeholder="Selecciona un personaje" />
            <br />
            <Turnstile key={captchaKey} onVerify={setCaptcha} />
            <button type="submit" className="search-items-button" disabled={busy || !character}>
              {busy ? 'Buscando' : 'BUSCAR ÍTEMS'}
            </button>
          </form>
        </div>
      ) : (
        <div id="search-items-response">
          <p className="yellow-info">Ítems borrados de {character}</p>
          {items.length === 0 ? (
            <p className="second-brown">No hay ítems borrados recuperables.</p>
          ) : (
            <table className="restore-item-table">
              <tbody>
                {items.map((it) => (
                  <tr key={it.recoverId}>
                    <td className="lefted">
                      <a href={`${ITEM_DB}/?item=${it.itemId}`} target="_blank" rel="noopener noreferrer">{it.name}</a>
                      {it.count > 1 ? ` x${it.count}` : ''}
                    </td>
                    <td className="real-info-box">
                      <button type="button" className="restore-item-button" value={it.recoverId} data-char={character} onClick={() => restore(it)} disabled={busy}>
                        Recuperar (100 PD)
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
          <br />
          <p><a id="a-select-other" href="#" onClick={(e) => { e.preventDefault(); reset() }}>Consultar otro personaje</a></p>
        </div>
      )}
      <hr />
      <div className="alert-message" id="search-items-response-msg" style={{ display: message ? 'block' : 'none' }}>
        {message && <span className={message.ok ? 'ok-form-response' : 'red-form-response'}>{message.text}</span>}
      </div>
    </div>
  )
}
