import { useMemo, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { IconSearch } from '@tabler/icons-react'
import { api, type KnowledgeCategory, type KnowledgeEntry } from '../lib/api'
import { useLang } from '../i18n/LanguageContext'
import type { TranslationKey } from '../i18n/translations'
import { PageHeader } from '../components/PageHeader'

const CATEGORIES: KnowledgeCategory[] = [
  'medicine',
  'survival',
  'security',
  'engineering',
  'comms',
]

export function KnowledgeBase() {
  const { t } = useLang()
  const [query, setQuery] = useState('')
  const [category, setCategory] = useState<KnowledgeCategory | null>(null)

  const { data } = useQuery({
    queryKey: ['knowledge'],
    queryFn: () => api.listKnowledge(),
  })

  const entries = useMemo(() => {
    let list = data?.entries ?? []
    if (category) list = list.filter((e) => e.category === category)
    const q = query.trim().toLowerCase()
    if (q) {
      list = list.filter((e) =>
        [e.title.lt, e.title.en, e.body.lt, e.body.en, ...e.tags]
          .join(' ')
          .toLowerCase()
          .includes(q)
      )
    }
    return list
  }, [data, category, query])

  return (
    <div>
      <PageHeader title={t('kb.title')} subtitle={t('kb.subtitle')} />

      <div className="relative mb-4">
        <IconSearch
          size={18}
          className="absolute left-3 top-1/2 -translate-y-1/2 text-arka-muted"
        />
        <input
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder={t('kb.search')}
          className="w-full rounded-lg border border-arka-border bg-arka-surface py-2.5 pl-10 pr-3 text-sm text-arka-text placeholder:text-arka-muted focus:border-arka-accent focus:outline-none"
        />
      </div>

      <div className="mb-5 flex flex-wrap gap-2">
        <Chip active={category === null} onClick={() => setCategory(null)}>
          {t('kb.all')}
        </Chip>
        {CATEGORIES.map((c) => (
          <Chip key={c} active={category === c} onClick={() => setCategory(c)}>
            {t(`cat.${c}` as TranslationKey)}
          </Chip>
        ))}
      </div>

      {entries.length === 0 ? (
        <p className="text-arka-muted">{t('kb.noResults')}</p>
      ) : (
        <div className="grid gap-3 md:grid-cols-2">
          {entries.map((e) => (
            <EntryCard key={e.id} entry={e} />
          ))}
        </div>
      )}

      <p className="mt-6 text-xs text-arka-muted">⚠ {t('kb.disclaimer')}</p>
    </div>
  )
}

function Chip({
  active,
  onClick,
  children,
}: {
  active: boolean
  onClick: () => void
  children: React.ReactNode
}) {
  return (
    <button
      onClick={onClick}
      className={`rounded-full border px-3 py-1 text-xs font-medium transition-colors ${
        active
          ? 'border-arka-accent bg-arka-accent/15 text-arka-accent'
          : 'border-arka-border text-arka-muted hover:text-arka-text'
      }`}
    >
      {children}
    </button>
  )
}

function EntryCard({ entry }: { entry: KnowledgeEntry }) {
  const { t, pick } = useLang()
  return (
    <article className="rounded-xl border border-arka-border bg-arka-surface p-4">
      <div className="mb-1 flex items-center gap-2">
        <span className="rounded bg-arka-surface-2 px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-arka-accent">
          {t(`cat.${entry.category}` as TranslationKey)}
        </span>
      </div>
      <h3 className="text-sm font-semibold text-arka-text">{pick(entry.title)}</h3>
      <p className="mt-1.5 text-xs leading-relaxed text-arka-muted">{pick(entry.body)}</p>
    </article>
  )
}
