'use client'
import React, { useState } from 'react'
import { ThemeCard } from '@/components/admin/ThemeCard'
import { usePBCollection } from '@/lib/hooks/usePBCollection'
import type { Theme } from '@/types'

export default function KnowledgePage() {
  const { items: themes, loading, error, refresh } = usePBCollection<Theme>('themes', {
    sort: '-created_at',
  })

  const [filter, setFilter] = useState<Theme['status'] | 'all'>('all')

  const filtered = filter === 'all' ? themes : themes.filter((t) => t.status === filter)

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--s-6)' }}>
      <div>
        <h1
          style={{
            margin: '0 0 var(--s-2)',
            fontSize: 'var(--t-h3)',
            fontWeight: 700,
            color: 'var(--fg)',
          }}
        >
          Knowledge base
        </h1>
        <p style={{ margin: 0, fontSize: 'var(--t-body)', color: 'var(--fg-muted)' }}>
          Themes extracted from ingested documents.
        </p>
      </div>

      {/* Filter tabs */}
      <div style={{ display: 'flex', gap: 'var(--s-2)', flexWrap: 'wrap' }}>
        {(['all', 'draft', 'published', 'rejected'] as const).map((f) => (
          <button
            key={f}
            onClick={() => setFilter(f)}
            style={{
              background: filter === f ? 'var(--accent)' : 'var(--bg-warm)',
              color: filter === f ? 'var(--paper)' : 'var(--fg)',
              border: '1.5px solid var(--cream)',
              borderRadius: 'var(--r-pill)',
              padding: 'var(--s-1) var(--s-4)',
              fontSize: 'var(--t-small)',
              fontFamily: 'var(--font-sans)',
              cursor: 'pointer',
              minHeight: '36px',
              textTransform: 'capitalize',
              transition: 'background 150ms',
            }}
          >
            {f}
          </button>
        ))}
      </div>

      {error && (
        <div
          style={{
            background: '#f8d7da',
            color: '#c0392b',
            borderRadius: 'var(--r-sm)',
            padding: 'var(--s-3) var(--s-4)',
            fontSize: 'var(--t-small)',
          }}
        >
          {error}
        </div>
      )}

      {loading ? (
        <div style={{ color: 'var(--fg-muted)', fontSize: 'var(--t-body)' }}>Loading…</div>
      ) : filtered.length === 0 ? (
        <div
          style={{
            textAlign: 'center',
            color: 'var(--fg-muted)',
            padding: 'var(--s-8, 64px) 0',
            fontSize: 'var(--t-body)',
          }}
        >
          {filter === 'all' ? 'No themes yet. Upload documents to get started.' : `No ${filter} themes.`}
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--s-3)' }}>
          {filtered.map((theme) => (
            <ThemeCard key={theme.id} theme={theme} onUpdate={refresh} />
          ))}
        </div>
      )}
    </div>
  )
}
