'use client'

import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { Turnstile } from '@/components/Turnstile'
import { CharacterSelect, type CharOption } from '@/components/CharacterSelect'

function tradeErrorKey(error?: string): string {
  switch (error) {
    case 'missingFields':
      return 'missingFields'
    case 'invalidAmount':
      return 'invalidAmount'
    case 'characterNotFound':
    case 'characterNotOwned':
      return 'characterInvalid'
    case 'captcha':
      return 'captcha'
    case 'wrongPassword':
      return 'wrongPassword'
    case 'invalidToken':
      return 'invalidToken'
    case 'insufficientPoints':
      return 'insufficientPoints'
    case 'codeNotFound':
      return 'codeNotFound'
    case 'codeUnavailable':
      return 'codeUnavailable'
    case 'cannotRedeemOwn':
      return 'cannotRedeemOwn'
    case 'characterOnline':
      return 'characterOnline'
    case 'insufficientGold':
      return 'insufficientGold'
    case 'creatorInsufficient':
      return 'creatorInsufficient'
    case 'locked':
      return 'locked'
    case 'deliveryFailed':
      return 'deliveryFailed'
    case 'notAuthenticated':
      return 'notAuthenticated'
    default:
      return 'generic'
  }
}

function PasswordInput({
  id,
  value,
  onChange,
  placeholder,
  maxLength,
}: {
  id: string
  value: string
  onChange: (v: string) => void
  placeholder: string
  maxLength: number
}) {
  const [show, setShow] = useState(false)
  return (
    <>
      <input
        type={show ? 'text' : 'password'}
        id={id}
        maxLength={maxLength}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
      />{' '}
      <span
        className={`far ${show ? 'fa-eye-slash' : 'fa-eye'} toggle-password`}
        role="button"
        tabIndex={0}
        onClick={() => setShow((s) => !s)}
      />
    </>
  )
}

/* ---------------------------------- VENTA ---------------------------------- */
function SellForm({ characters, visible }: { characters: CharOption[]; visible: boolean }) {
  const t = useTranslations('Points')
  const tradeError = (error?: string) => t(`trade.errors.${tradeErrorKey(error)}`)
  const [points, setPoints] = useState('')
  const [gold, setGold] = useState('')
  const [character, setCharacter] = useState('')
  const [password, setPassword] = useState('')
  const [token, setToken] = useState('')
  const [captcha, setCaptcha] = useState('')
  const [busy, setBusy] = useState(false)
  const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)
  const [created, setCreated] = useState<{ code: string; points: number; gold: number } | null>(null)

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    if (busy) return
    setBusy(true)
    setMessage(null)
    setCreated(null)
    try {
      const res = await fetch('/api/dpoints/trade/create', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({
          points: Number(points),
          gold: Number(gold),
          character,
          password,
          token: token.trim(),
          turnstile: captcha,
        }),
      })
      const data: { success?: boolean; error?: string; code?: { code: string; points: number; gold: number } } = await res.json()
      if (data.success && data.code) {
        setCreated(data.code)
        setMessage({ ok: true, text: t('trade.codeCreated') })
        setPoints('')
        setGold('')
        setPassword('')
        setToken('')
      } else {
        setMessage({ ok: false, text: tradeError(data.error) })
      }
    } catch {
      setMessage({ ok: false, text: tradeError() })
    } finally {
      setBusy(false)
    }
  }

  return (
    <div id="trade-sell-div" style={{ display: visible ? 'block' : 'none' }}>
      <form onSubmit={handleSubmit} acceptCharset="utf-8">
        <table className="middle-center-table">
          <tbody>
            <tr><td>{t('trade.sellPointsLabel')}</td></tr>
            <tr><td><input type="number" maxLength={5} min="1" max="99999" step="1" value={points} onChange={(e) => setPoints(e.target.value)} placeholder={t('trade.sellPointsPlaceholder')} required /></td></tr>
            <tr><td>{t('trade.sellGoldLabel')}</td></tr>
            <tr><td><input type="number" maxLength={5} min="1" max="99999" step="1" value={gold} onChange={(e) => setGold(e.target.value)} placeholder={t('trade.sellGoldPlaceholder')} required /></td></tr>
            <tr><td>{t('trade.sellCharLabel')}</td></tr>
            <tr><td>
              <CharacterSelect characters={characters} value={character} onChange={setCharacter} placeholder={t('trade.selectCharacter')} />
            </td></tr>
            <tr><td><br /><PasswordInput id="password-sell" value={password} onChange={setPassword} placeholder={t('trade.passwordPlaceholder')} maxLength={16} /></td></tr>
            <tr><td><input type="text" maxLength={6} value={token} onChange={(e) => setToken(e.target.value)} placeholder={t('trade.tokenPlaceholder')} required /></td></tr>
            <tr><td><Turnstile onVerify={setCaptcha} /></td></tr>
            <tr><td><button type="submit" className="trade-points-sell-button" disabled={busy}>{busy ? t('trade.creating') : t('trade.createButton')}</button></td></tr>
          </tbody>
        </table>
      </form>
      <hr />
      <div className="alert-message" id="trade-points-sell-response" style={{ display: message || created ? 'block' : 'none' }}>
        {message && <span className={message.ok ? 'ok-form-response' : 'red-form-response'}>{message.text}</span>}
        {created && (
          <fieldset>
            <legend>{t('trade.createdLegend')}</legend>
            <div className="separate2">
              <p>{t('trade.codeIdLabel')} <span className="green-info2">{created.code}</span></p>
              <p>{t.rich('trade.createdValue', { points: created.points, gold: created.gold, s: (c) => <span>{c}</span> })}</p>
              <p className="second-brown">{t('trade.createdHint')}</p>
            </div>
          </fieldset>
        )}
      </div>
    </div>
  )
}

/* ---------------------------------- COMPRA --------------------------------- */
function BuyForm({ characters, visible }: { characters: CharOption[]; visible: boolean }) {
  const t = useTranslations('Points')
  const tradeError = (error?: string) => t(`trade.errors.${tradeErrorKey(error)}`)
  const [code, setCode] = useState('')
  const [character, setCharacter] = useState('')
  const [password, setPassword] = useState('')
  const [token, setToken] = useState('')
  const [captcha, setCaptcha] = useState('')
  const [busy, setBusy] = useState(false)
  const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null)
  const [checkInfo, setCheckInfo] = useState<{ points: number; gold: number } | null>(null)

  async function handleCheck() {
    if (busy || !code.trim()) return
    setBusy(true)
    setMessage(null)
    setCheckInfo(null)
    try {
      const res = await fetch('/api/dpoints/trade/check', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ code: code.trim() }),
      })
      const data: { success?: boolean; error?: string; points?: number; gold?: number } = await res.json()
      if (data.success && data.points != null && data.gold != null) {
        setCheckInfo({ points: data.points, gold: data.gold })
        setMessage({ ok: true, text: t('trade.checkResult', { points: data.points, gold: data.gold }) })
      } else {
        setMessage({ ok: false, text: tradeError(data.error) })
      }
    } catch {
      setMessage({ ok: false, text: tradeError() })
    } finally {
      setBusy(false)
    }
  }

  async function handleRedeem(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    if (busy) return
    if (!window.confirm(t('trade.redeemConfirm'))) return
    setBusy(true)
    setMessage(null)
    try {
      const res = await fetch('/api/dpoints/trade/redeem', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ code: code.trim(), character, password, token: token.trim(), turnstile: captcha }),
      })
      const data: { success?: boolean; error?: string; points?: number; gold?: number } = await res.json()
      if (data.success) {
        setMessage({ ok: true, text: t('trade.redeemSuccess', { points: data.points ?? 0, gold: data.gold ?? 0, character }) })
        setCode('')
        setPassword('')
        setToken('')
        setCheckInfo(null)
      } else {
        setMessage({ ok: false, text: tradeError(data.error) })
      }
    } catch {
      setMessage({ ok: false, text: tradeError() })
    } finally {
      setBusy(false)
    }
  }

  return (
    <div id="trade-buy-div" style={{ display: visible ? 'block' : 'none' }}>
      <form onSubmit={handleRedeem} acceptCharset="utf-8">
        <table className="middle-center-table">
          <tbody>
            <tr><td>{t('trade.buyCodeLabel')}</td></tr>
            <tr><td><input type="text" maxLength={25} value={code} onChange={(e) => setCode(e.target.value)} placeholder={t('trade.buyCodePlaceholder')} required /></td></tr>
            {checkInfo && (
              <tr><td><p className="green-info2">{t('trade.checkInfo', { points: checkInfo.points, gold: checkInfo.gold })}</p></td></tr>
            )}
            <tr><td>{t('trade.buyCharLabel')}</td></tr>
            <tr><td>
              <CharacterSelect characters={characters} value={character} onChange={setCharacter} placeholder={t('trade.selectCharacter')} />
            </td></tr>
            <tr><td><br /><PasswordInput id="password-buy" value={password} onChange={setPassword} placeholder={t('trade.passwordPlaceholder')} maxLength={16} /></td></tr>
            <tr><td><input type="text" maxLength={6} value={token} onChange={(e) => setToken(e.target.value)} placeholder={t('trade.tokenPlaceholder')} required /></td></tr>
            <tr><td><Turnstile onVerify={setCaptcha} /></td></tr>
            <tr><td><button type="button" className="trade-points-check-button" disabled={busy} onClick={handleCheck}>{t('trade.checkButton')}</button></td></tr>
            <tr><td><button type="submit" className="trade-points-buy-button" disabled={busy}>{busy ? t('trade.processing') : t('trade.redeemButton')}</button></td></tr>
          </tbody>
        </table>
      </form>
      <hr />
      <div className="alert-message" id="trade-points-buy-response" style={{ display: message ? 'block' : 'none' }}>
        {message && <span className={message.ok ? 'ok-form-response' : 'red-form-response'}>{message.text}</span>}
      </div>
    </div>
  )
}

export function TradePointsForm({ characters }: { characters: CharOption[] }) {
  const t = useTranslations('Points')
  // Como el original: al cargar no se muestra ningún formulario; se revela al
  // pulsar VENTA o COMPRA.
  const [active, setActive] = useState<'sell' | 'buy' | null>(null)

  if (characters.length === 0) {
    return (
      <div className="centered">
        <br />
        <span>{t('trade.noCharacters')}</span>
      </div>
    )
  }

  return (
    <div className="centered">
      <br />
      <br />
      <button
        type="button"
        id="trade-sell-a"
        className={`trade-option-button${active === 'sell' ? ' dnt-selected' : ''}`}
        onClick={() => setActive('sell')}
      >
        {t('trade.sellTab')}
      </button>
      <button
        type="button"
        id="trade-buy-a"
        className={`trade-option-button${active === 'buy' ? ' dnt-selected' : ''}`}
        onClick={() => setActive('buy')}
      >
        {t('trade.buyTab')}
      </button>
      <br />
      <SellForm characters={characters} visible={active === 'sell'} />
      <BuyForm characters={characters} visible={active === 'buy'} />
      <br />
    </div>
  )
}
