'use client'

import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { useRouter } from '@/i18n/navigation'
import type { RecruitRewardView } from '@/lib/recruit-claim'

export function RecruitClaim({
  rewards,
  characters,
  level80Count,
}: {
  rewards: RecruitRewardView[]
  characters: string[]
  level80Count: number
}) {
  const t = useTranslations('RecruitClaim')
  const router = useRouter()
  const [character, setCharacter] = useState(characters[0] ?? '')
  const [busyId, setBusyId] = useState<number | null>(null)
  const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null)

  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()
      setMsg({ ok: Boolean(d.success), text: t(d.message ?? 'deliveryError', { reward: reward.reward_name, character }) })
      if (d.success) router.refresh()
    } catch {
      setMsg({ ok: false, text: t('deliveryError') })
    } finally {
      setBusyId(null)
    }
  }

  return (
    <div>
      <div className="info-box-light separate">
        <p className="second-brown">
          {t('level80Friends')}: <span className="yellow-info">{level80Count}</span>
        </p>
        {characters.length > 0 ? (
          <p>
            <span className="second-brown">{t('deliverTo')} </span>
            <select value={character} onChange={(e) => setCharacter(e.target.value)}>
              {characters.map((c) => (
                <option key={c} value={c}>
                  {c}
                </option>
              ))}
            </select>
          </p>
        ) : (
          <p className="second-brown">{t('noCharacters')}</p>
        )}
      </div>

      <div className="alert-message" style={{ display: msg ? 'block' : 'none' }}>
        {msg && <span className={msg.ok ? 'ok-form-response' : 'red-form-response'}>{msg.text}</span>}
      </div>

      {rewards.length === 0 ? (
        <p className="second-brown">{t('noRewards')}</p>
      ) : (
        <div className="centered">
          {rewards.map((r) => {
            const eligible = level80Count >= r.required_friends
            return (
              <div key={r.id} className="raf-box">
                <a href={r.item_link} target="_blank" rel="noopener noreferrer" className="yellow-info">
                  {r.reward_name}
                </a>
                <p className="second-brown small-font">
                  {t('requires', { n: r.required_friends })} · item {r.item_id} ×{r.item_quantity}
                </p>
                <br />
                {r.claimed ? (
                  <span className="green-info">
                    <i className="fas fa-check"></i> {t('claimed')}
                  </span>
                ) : (
                  <button
                    type="button"
                    onClick={() => claim(r)}
                    disabled={!eligible || busyId !== null || characters.length === 0}
                    title={!eligible ? t('notEnoughFriends') : undefined}
                  >
                    {busyId === r.id ? t('claiming') : eligible ? t('claim') : t('locked')}
                  </button>
                )}
              </div>
            )
          })}
        </div>
      )}
    </div>
  )
}
