import { useState } from 'react'
import { IconInfoCircle, IconPlus } from '@tabler/icons-react'
import { useLang } from '../i18n/LanguageContext'
import { PageHeader } from '../components/PageHeader'
import { CatalogView } from '../components/CatalogView'
import { AddResourceForm } from '../components/AddResourceForm'
import type { ResourceType } from '../lib/api'

export function Downloads() {
  const { t } = useLang()
  const [filter, setFilter] = useState<ResourceType | null>(null)
  const [showForm, setShowForm] = useState(false)

  const chips: { key: ResourceType | null; label: string }[] = [
    { key: null, label: t('dl.all') },
    { key: 'wiki', label: t('dl.wiki') },
    { key: 'map', label: t('dl.map') },
  ]

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

      <div className="mb-5 flex flex-wrap items-center justify-between gap-3">
        <div className="flex flex-wrap gap-2">
          {chips.map((c) => (
            <button
              key={c.key ?? 'all'}
              onClick={() => setFilter(c.key)}
              className={`rounded-full border px-3 py-1 text-xs font-medium transition-colors ${
                filter === c.key
                  ? 'border-arka-accent bg-arka-accent/15 text-arka-accent'
                  : 'border-arka-border text-arka-muted hover:text-arka-text'
              }`}
            >
              {c.label}
            </button>
          ))}
        </div>
        <button
          onClick={() => setShowForm((v) => !v)}
          className="inline-flex items-center gap-1.5 rounded-lg border border-arka-border px-3 py-1.5 text-xs font-medium text-arka-text transition-colors hover:border-arka-accent hover:text-arka-accent"
        >
          <IconPlus size={15} />
          {t('dl.addUrl')}
        </button>
      </div>

      {showForm && <AddResourceForm onDone={() => setShowForm(false)} />}

      <CatalogView type={filter ?? undefined} />

      <p className="mt-6 flex items-center gap-1.5 text-xs text-arka-muted">
        <IconInfoCircle size={14} /> {t('dl.hint')}
      </p>
    </div>
  )
}
