import { getTranslations, setRequestLocale } from 'next-intl/server'
import { Link } from '@/i18n/navigation'
import { searchCharacters, searchItems, searchGuilds } from '@/lib/armory'
import { raceName, className, classColor } from '@/lib/wow-data'
import { wowheadUrl, wowheadData } from '@/lib/wowhead'
import { PageShell } from '@/components/PageShell'
import { ArmorySearchBox } from '@/components/ArmorySearchBox'
import { WowheadRefresh } from '@/components/WowheadRefresh'

export const dynamic = 'force-dynamic'

const TABS = ['characters', 'items', 'guilds'] as const
type Tab = (typeof TABS)[number]

export default async function ArmoryPage({
  params,
  searchParams,
}: {
  params: Promise<{ locale: string }>
  searchParams: Promise<{ tab?: string; q?: string }>
}) {
  const { locale } = await params
  setRequestLocale(locale)
  const t = await getTranslations('Armory')
  const sp = await searchParams
  const tab: Tab = TABS.includes(sp.tab as Tab) ? (sp.tab as Tab) : 'characters'
  const q = (sp.q ?? '').trim()
  const hasQuery = q.length >= 3

  const characters = hasQuery && tab === 'characters' ? await searchCharacters(q) : []
  const items = hasQuery && tab === 'items' ? await searchItems(q, locale) : []
  const guilds = hasQuery && tab === 'guilds' ? await searchGuilds(q) : []

  const tabLabel: Record<Tab, string> = {
    characters: t('tabCharacters'),
    items: t('tabItems'),
    guilds: t('tabGuilds'),
  }

  return (
    <PageShell title={t('title')}>
      <div className="main-wide">
        <WowheadRefresh dep={`${tab}-${q}`} />
        <ArmorySearchBox tab={tab} initialQuery={q} />

        <div className="armory-tabs">
          {TABS.map((tb) => (
            <Link
              key={tb}
              href={`/armory?tab=${tb}${q ? `&q=${encodeURIComponent(q)}` : ''}`}
              className={`armory-tab${tb === tab ? ' active' : ''}`}
            >
              {tabLabel[tb]}
            </Link>
          ))}
        </div>

        {!hasQuery ? (
          <p className="armory-hint">{t('searchHint')}</p>
        ) : tab === 'characters' ? (
          characters.length === 0 ? (
            <p className="armory-hint">{t('noResults')}</p>
          ) : (
            <div className="armory-list">
              {characters.map((c) => (
                <Link key={c.guid} href={`/armory/character/${c.guid}`} className="armory-row">
                  <span className="armory-name" style={{ color: classColor(c.class) }}>
                    {c.name}
                  </span>
                  <span className="armory-meta">
                    {t('level')} {c.level} · {raceName(c.race, locale)} · {className(c.class, locale)}
                  </span>
                </Link>
              ))}
            </div>
          )
        ) : tab === 'items' ? (
          items.length === 0 ? (
            <p className="armory-hint">{t('noResults')}</p>
          ) : (
            <div className="armory-list">
              {items.map((it) => (
                <div key={it.entry} className="armory-row">
                  <a
                    href={wowheadUrl('item', it.entry, locale)}
                    data-wowhead={wowheadData('item', it.entry, locale)}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="armory-name"
                  >
                    {it.name}
                  </a>
                  <span className="armory-meta">
                    {t('itemLevel')} {it.itemLevel}
                  </span>
                </div>
              ))}
            </div>
          )
        ) : guilds.length === 0 ? (
          <p className="armory-hint">{t('noResults')}</p>
        ) : (
          <div className="armory-list">
            {guilds.map((g) => (
              <Link key={g.guildid} href={`/armory/guild/${g.guildid}`} className="armory-row">
                <span className="armory-name">{g.name}</span>
                <span className="armory-meta">
                  {g.members} {t('members')}
                </span>
              </Link>
            ))}
          </div>
        )}
      </div>
    </PageShell>
  )
}
