'use client'

import { useState } from 'react'
import type { RecruitRewardView } from '@/lib/recruit-claim'
import type { CharOption } from '@/components/CharacterSelect'

const ICON_BASE = 'https://wotlk.ultimowow.com/static/images/wow/icons/tiny'

function claimError(message?: string): string {
  switch (message) {
    case 'requirementsNotMet':
      return 'Aún no cumples los requisitos para esta recompensa.'
    case 'alreadyClaimed':
      return 'Esta recompensa ya fue reclamada.'
    case 'invalidCharacter':
      return 'Personaje no válido.'
    case 'notFound':
      return 'Recompensa no encontrada.'
    default:
      return 'No se pudo reclamar la recompensa. Inténtalo de nuevo.'
  }
}

/**
 * Panel de Recluta a un amigo: estadísticas de la cuenta + tabla de recompensas
 * (objetivo, objeto y estado) con botón para reclamar las disponibles.
 */
export function RecruitPanel({
  rewards,
  characters,
  level80Count,
  isRecruited,
  recruitedCount,
}: {
  rewards: RecruitRewardView[]
  characters: CharOption[]
  level80Count: number
  isRecruited: boolean
  recruitedCount: number
}) {
  const [character, setCharacter] = useState(characters[0]?.name ?? '')
  const selectedCss = characters.find((c) => c.name === character)?.classCss
  const [busyId, setBusyId] = useState<number | null>(null)
  const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null)

  const claimedCount = rewards.filter((r) => r.claimed).length
  const available = rewards.filter((r) => !r.claimed && level80Count >= r.required_friends)

  async function claim(reward: RecruitRewardView) {
    if (busyId !== null || !character) return
    setBusyId(reward.id)
    setMsg(null)
    try {
      const res = await fetch('/api/recruit/claim', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ rewardId: reward.id, character }),
      })
      const d: { success?: boolean; message?: string } = await res.json()
      if (d.success) {
        window.location.reload()
        return
      }
      setMsg({ ok: false, text: claimError(d.message) })
      setBusyId(null)
    } catch {
      setMsg({ ok: false, text: claimError() })
      setBusyId(null)
    }
  }

  function rewardCell(r: RecruitRewardView) {
    const [quality, icon] = (r.icon_class || '').split(' ')
    return (
      <>
        <a
          href={r.item_link}
          target="_blank"
          rel="noopener noreferrer"
          className={`icontinyl ${quality || ''}`}
          style={{ paddingLeft: '18px', background: `url('${ICON_BASE}/${icon}.gif') left center no-repeat` }}
        >
          {r.reward_name}
        </a>
        {r.item_quantity > 1 ? ` x${r.item_quantity}` : ''}
      </>
    )
  }

  return (
    <>
      <p className="lefted">Cuenta reclutada: <span>{isRecruited ? 'Sí' : 'No'}</span></p>
      <p className="lefted">Amigos reclutados: <span>{recruitedCount}</span></p>
      <p className="lefted">Amigos reclutados al nivel 80: <span>{level80Count}</span></p>
      <p className="lefted">Recompensas reclamadas: <span>{claimedCount}/{rewards.length}</span></p>
      <br />

      {characters.length > 0 && (
        <p className="lefted">
          Recibir recompensas en:{' '}
          <select value={character} onChange={(e) => setCharacter(e.target.value)} className={['account-select', selectedCss].filter(Boolean).join(' ')}>
            {characters.map((c) => (
              <option key={c.name} value={c.name} className={c.classCss ? `${c.classCss} big-font` : undefined}>{c.name}</option>
            ))}
          </select>
        </p>
      )}
      {msg && <p className={msg.ok ? 'green-info' : 'red-info'}>{msg.text}</p>}

      <table className="char-center-table">
        <tbody>
          <tr>
            <th>Amigos reclutados</th>
            <th>Recompensa</th>
            <th>Estado</th>
          </tr>
          {rewards.map((r) => {
            const eligible = level80Count >= r.required_friends
            return (
              <tr key={r.id}>
                <td><span>{r.required_friends} {r.required_friends === 1 ? 'amigo' : 'amigos'} al nivel 80</span></td>
                <td>{rewardCell(r)}</td>
                <td>
                  {r.claimed ? (
                    <span className="green-info"><i className="fas fa-check"></i> Reclamado</span>
                  ) : eligible ? (
                    <button type="button" className="nw-tool-btn" onClick={() => claim(r)} disabled={busyId !== null}>
                      {busyId === r.id ? '…' : 'Reclamar'}
                    </button>
                  ) : (
                    <span>Sin reclamar</span>
                  )}
                </td>
              </tr>
            )
          })}
        </tbody>
      </table>

      <br />
      <hr />
      <p>RECOMPENSAS DISPONIBLES</p>
      <hr />
      {available.length === 0 ? (
        <span>Recluta amigos para poder reclamar las recompensas</span>
      ) : (
        <span className="green-info">
          Tienes {available.length} recompensa{available.length === 1 ? '' : 's'} lista{available.length === 1 ? '' : 's'} para reclamar
        </span>
      )}
    </>
  )
}
