'use client'

import { useState } from 'react'
import { useTranslations, useLocale } from 'next-intl'
import { CharacterSelect, type CharOption } from '@/components/CharacterSelect'
import { PaymentMethodSelect, pdCostOf, type PayMethod } from '@/components/PaymentMethodSelect'
import { WowheadLink } from '@/components/WowheadLink'
import { Turnstile } from '@/components/Turnstile'

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

function itemsError(t: ReturnType<typeof useTranslations>, error?: string, minutes?: number): string {
  switch (error) {
    case 'characterNotOwned':
      return t('restoreItems.errors.characterNotOwned')
    case 'cooldown':
      return t('restoreItems.errors.cooldown', { minutes: minutes ?? 0 })
    case 'soapError':
      return t('restoreItems.errors.soapError')
    case 'insufficientPoints':
      return t('restoreItems.errors.insufficientPoints')
    case 'captcha':
      return t('restoreItems.errors.captcha')
    case 'notAuthenticated':
      return t('restoreItems.errors.notAuthenticated')
    default:
      return t('restoreItems.errors.default')
  }
}

export function RestoreItemsForm({ characters, price, pdBalance }: { characters: CharOption[]; price: number; pdBalance: number }) {
  const t = useTranslations('CharService')
  const tpay = useTranslations('Pay')
  const locale = useLocale()
  const [character, setCharacter] = useState('')
  const [method, setMethod] = useState<PayMethod>(pdBalance >= pdCostOf(price) ? 'pd' : 'sumup')
  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)

  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: t('restoreItems.noDeletedItemsMsg') })
      } else {
        setMessage({ ok: false, text: itemsError(t, data.error, data.minutes) })
      }
    } catch {
      setMessage({ ok: false, text: itemsError(t) })
    } finally {
      setBusy(false)
      setCaptcha('')
      setCaptchaKey((k) => k + 1)
    }
  }

  async function restore(item: DeletedItem) {
    if (busy) return
    if (!window.confirm(t('restoreItems.confirm', { name: item.name, price }))) return
    setBusy(true)
    setMessage(null)
    try {
      const res = await fetch('/api/character/restore-item/checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ character, recover_id: String(item.recoverId), provider: method, locale }),
      })
      const data: { success?: boolean; url?: string; error?: string; message?: string } = await res.json()
      if (data.success && data.url) {
        window.location.assign(data.url) // éxito PD, o checkout de SumUp/Stripe
        return
      }
      const payErr = data.error && tpay.has(`errors.${data.error}`) ? tpay(`errors.${data.error}`) : undefined
      setMessage({ ok: false, text: data.message || payErr || itemsError(t, data.error) })
      setBusy(false)
    } catch {
      setMessage({ ok: false, text: itemsError(t) })
      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="ns-search-items-form" onSubmit={search} acceptCharset="utf-8">
            <CharacterSelect characters={characters} value={character} onChange={setCharacter} placeholder={t('restoreItems.selectPlaceholder')} />
            <br />
            <Turnstile key={captchaKey} onVerify={setCaptcha} />
            <button type="submit" className="search-items-button" disabled={busy || !character}>
              {busy ? t('restoreItems.searching') : t('restoreItems.search')}
            </button>
          </form>
        </div>
      ) : (
        <div id="search-items-response">
          <p className="yellow-info">{t('restoreItems.deletedItemsOf', { character })}</p>
          {items.length === 0 ? (
            <p className="second-brown">{t('restoreItems.noDeletedItems')}</p>
          ) : (
            <>
            <PaymentMethodSelect value={method} onChange={setMethod} priceEur={price} pdBalance={pdBalance} />
            <table className="restore-item-table">
              <tbody>
                {items.map((it) => (
                  <tr key={it.recoverId}>
                    <td className="lefted">
                      <WowheadLink id={it.itemId}>{it.name}</WowheadLink>
                      {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}>
                        {t('restoreItems.restoreItem', { price })}
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
            </>
          )}
          <br />
          <p><a id="a-select-other" href="#" onClick={(e) => { e.preventDefault(); reset() }}>{t('restoreItems.queryOther')}</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>
  )
}
