'use client'

import { useEffect, useRef, useState } from 'react'
import { useTranslations, useLocale } from 'next-intl'
import { useRouter } from '@/i18n/navigation'
import { classColor } from '@/lib/wow-data'
import { wowheadUrl } from '@/lib/wowhead'

interface Suggestions {
  characters: { guid: number; name: string; level: number; class: number; sub: string }[]
  items: { entry: number; name: string; quality: number; itemLevel: number }[]
  guilds: { guildid: number; name: string; members: number }[]
}

const EMPTY: Suggestions = { characters: [], items: [], guilds: [] }

/**
 * Buscador de la armería con autocompletar tipo wowhead: al teclear (≥1 carácter)
 * muestra un desplegable con personajes, ítems y hermandades que coinciden. Enter o
 * el botón hacen la búsqueda completa; clic en una sugerencia va directo.
 */
export function ArmorySearchBox({ tab, initialQuery }: { tab: string; initialQuery: string }) {
  const t = useTranslations('Armory')
  const locale = useLocale()
  const router = useRouter()
  const [q, setQ] = useState(initialQuery)
  const [sug, setSug] = useState<Suggestions>(EMPTY)
  const [open, setOpen] = useState(false)
  const boxRef = useRef<HTMLDivElement>(null)

  // Buscar sugerencias con debounce.
  useEffect(() => {
    const query = q.trim()
    if (query.length < 1) {
      setSug(EMPTY)
      return
    }
    const ctrl = new AbortController()
    const timer = setTimeout(async () => {
      try {
        const res = await fetch(`/api/armory/suggest?q=${encodeURIComponent(query)}&locale=${locale}`, {
          signal: ctrl.signal,
        })
        const data: Suggestions = await res.json()
        setSug(data)
        setOpen(true)
      } catch {
        /* abortado o error */
      }
    }, 200)
    return () => {
      clearTimeout(timer)
      ctrl.abort()
    }
  }, [q, locale])

  // Cerrar al hacer clic fuera.
  useEffect(() => {
    function onClick(e: MouseEvent) {
      if (boxRef.current && !boxRef.current.contains(e.target as Node)) setOpen(false)
    }
    document.addEventListener('mousedown', onClick)
    return () => document.removeEventListener('mousedown', onClick)
  }, [])

  function fullSearch(e: React.FormEvent) {
    e.preventDefault()
    const query = q.trim()
    if (query.length < 3) return
    setOpen(false)
    router.push(`/armory?tab=${tab}&q=${encodeURIComponent(query)}`)
  }

  function go(href: string) {
    setOpen(false)
    router.push(href)
  }

  const hasResults = sug.characters.length + sug.items.length + sug.guilds.length > 0

  return (
    <div className="armory-search" ref={boxRef}>
      <form onSubmit={fullSearch} className="armory-search-form">
        <input
          className="forum-input"
          value={q}
          onChange={(e) => setQ(e.target.value)}
          onFocus={() => q.trim() && setOpen(true)}
          placeholder={t('searchPlaceholder')}
          maxLength={100}
          autoComplete="off"
        />
        <button type="submit" className="nice_button">
          {t('search')}
        </button>
      </form>

      {open && hasResults && (
        <div className="armory-suggest">
          {sug.characters.length > 0 && (
            <div className="armory-suggest-group">
              <div className="armory-suggest-head">{t('tabCharacters')}</div>
              {sug.characters.map((c) => (
                <button key={`c${c.guid}`} className="armory-suggest-item" onClick={() => go(`/armory/character/${c.guid}`)}>
                  <span style={{ color: classColor(c.class) }}>{c.name}</span>
                  <span className="armory-suggest-sub">
                    {t('level')} {c.level} · {c.sub}
                  </span>
                </button>
              ))}
            </div>
          )}
          {sug.items.length > 0 && (
            <div className="armory-suggest-group">
              <div className="armory-suggest-head">{t('tabItems')}</div>
              {sug.items.map((it) => (
                <a
                  key={`i${it.entry}`}
                  className="armory-suggest-item"
                  href={wowheadUrl('item', it.entry, locale)}
                  target="_blank"
                  rel="noopener noreferrer"
                  onClick={() => setOpen(false)}
                >
                  <span className={`q${it.quality}`}>{it.name}</span>
                  <span className="armory-suggest-sub">
                    {t('itemLevel')} {it.itemLevel}
                  </span>
                </a>
              ))}
            </div>
          )}
          {sug.guilds.length > 0 && (
            <div className="armory-suggest-group">
              <div className="armory-suggest-head">{t('tabGuilds')}</div>
              {sug.guilds.map((g) => (
                <button key={`g${g.guildid}`} className="armory-suggest-item" onClick={() => go(`/armory/guild/${g.guildid}`)}>
                  <span>{g.name}</span>
                  <span className="armory-suggest-sub">
                    {g.members} {t('members')}
                  </span>
                </button>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  )
}
