'use client'
import React, { useState } from 'react'
import Link from 'next/link'
import { usePBCollection } from '@/lib/hooks/usePBCollection'
import { StatusBadge } from '@/components/ui/StatusBadge'
import type { Topic, Theme } from '@/types'

type Difficulty = Topic['difficulty'] | 'all'

export default function LibraryPage() {
  const { items: topics, loading } = usePBCollection<Topic>('topics', {
    filter: 'status="published"',
    expand: 'theme',
    sort: 'theme,difficulty,title',
  })
  const { items: themes } = usePBCollection<Theme>('themes', {
    filter: 'status="published"',
    sort: 'title',
  })

  const [search, setSearch] = useState('')
  const [difficulty, setDifficulty] = useState<Difficulty>('all')
  const [themeFilter, setThemeFilter] = useState<string>('all')

  const filtered = topics.filter((t) => {
    const matchSearch =
      search === '' ||
      t.title.toLowerCase().includes(search.toLowerCase()) ||
      t.key_terms.some((k) => k.toLowerCase().includes(search.toLowerCase()))
    const matchDiff = difficulty === 'all' || t.difficulty === difficulty
    const matchTheme = themeFilter === 'all' || t.theme === themeFilter
    return matchSearch && matchDiff && matchTheme
  })

  // Group by theme
  const grouped = new Map<string, Topic[]>()
  for (const topic of filtered) {
    const list = grouped.get(topic.theme) ?? []
    list.push(topic)
    grouped.set(topic.theme, list)
  }

  const themeMap = new Map(themes.map((t) => [t.id, t]))

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--s-5)' }}>
      <div>
        <h1
          style={{
            margin: '0 0 var(--s-2)',
            fontSize: 'var(--t-h3)',
            fontWeight: 700,
            color: 'var(--fg)',
          }}
        >
          Library
        </h1>
        <p style={{ margin: 0, fontSize: 'var(--t-body)', color: 'var(--fg-muted)' }}>
          Browse all published topics.
        </p>
      </div>

      {/* Search */}
      <input
        type="search"
        value={search}
        onChange={(e) => setSearch(e.target.value)}
        placeholder="Search topics or key terms…"
        style={{
          width: '100%',
          borderRadius: 'var(--r-md)',
          border: '1.5px solid var(--cream)',
          padding: 'var(--s-3) var(--s-4)',
          fontSize: 'var(--t-body)',
          fontFamily: 'var(--font-sans)',
          color: 'var(--fg)',
          background: 'var(--bg)',
          outline: 'none',
          minHeight: '44px',
        }}
      />

      {/* Filters */}
      <div style={{ display: 'flex', gap: 'var(--s-2)', flexWrap: 'wrap' }}>
        {(['all', 'introductory', 'intermediate', 'advanced'] as const).map((d) => (
          <button
            key={d}
            onClick={() => setDifficulty(d)}
            style={{
              background: difficulty === d ? 'var(--accent)' : 'var(--bg-warm)',
              color: difficulty === d ? 'var(--paper)' : 'var(--fg)',
              border: '1.5px solid var(--cream)',
              borderRadius: 'var(--r-pill)',
              padding: 'var(--s-1) var(--s-3)',
              fontSize: 'var(--t-small)',
              fontFamily: 'var(--font-sans)',
              cursor: 'pointer',
              minHeight: '36px',
              textTransform: 'capitalize',
              transition: 'background 150ms',
            }}
          >
            {d}
          </button>
        ))}
      </div>

      {/* Theme filter */}
      {themes.length > 0 && (
        <select
          value={themeFilter}
          onChange={(e) => setThemeFilter(e.target.value)}
          style={{
            borderRadius: 'var(--r-sm)',
            border: '1.5px solid var(--cream)',
            padding: 'var(--s-2) var(--s-3)',
            fontSize: 'var(--t-body)',
            fontFamily: 'var(--font-sans)',
            color: 'var(--fg)',
            background: 'var(--bg)',
            outline: 'none',
            minHeight: '44px',
          }}
        >
          <option value="all">All themes</option>
          {themes.map((t) => (
            <option key={t.id} value={t.id}>
              {t.title}
            </option>
          ))}
        </select>
      )}

      {loading ? (
        <div style={{ color: 'var(--fg-muted)', fontSize: 'var(--t-body)' }}>Loading…</div>
      ) : filtered.length === 0 ? (
        <div style={{ color: 'var(--fg-muted)', fontSize: 'var(--t-body)', textAlign: 'center', padding: 'var(--s-6)' }}>
          No topics match your search.
        </div>
      ) : (
        Array.from(grouped.entries()).map(([themeId, themeTopics]) => {
          const theme = themeMap.get(themeId)
          return (
            <div key={themeId} style={{ display: 'flex', flexDirection: 'column', gap: 'var(--s-3)' }}>
              <h2
                style={{
                  margin: 0,
                  fontSize: 'var(--t-small)',
                  fontWeight: 700,
                  color: 'var(--fg-muted)',
                  textTransform: 'uppercase',
                  letterSpacing: '0.05em',
                  fontFamily: 'var(--font-mono)',
                }}
              >
                {theme?.title ?? themeId}
              </h2>
              {themeTopics.map((topic) => (
                <Link
                  key={topic.id}
                  href={`/app/library/${topic.id}`}
                  style={{ textDecoration: 'none' }}
                >
                  <div
                    style={{
                      background: 'var(--bg-warm)',
                      borderRadius: 'var(--r-sm)',
                      padding: 'var(--s-3) var(--s-4)',
                      display: 'flex',
                      alignItems: 'center',
                      gap: 'var(--s-3)',
                      minHeight: '56px',
                      transition: 'background 150ms',
                    }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.background = 'var(--cream)'
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.background = 'var(--bg-warm)'
                    }}
                  >
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <p
                        style={{
                          margin: '0 0 var(--s-1)',
                          fontWeight: 600,
                          fontSize: 'var(--t-body)',
                          color: 'var(--fg)',
                          overflow: 'hidden',
                          textOverflow: 'ellipsis',
                          whiteSpace: 'nowrap',
                        }}
                      >
                        {topic.title}
                      </p>
                      {topic.key_terms.length > 0 && (
                        <p
                          style={{
                            margin: 0,
                            fontSize: 'var(--t-small)',
                            color: 'var(--fg-muted)',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap',
                          }}
                        >
                          {topic.key_terms.slice(0, 4).join(', ')}
                        </p>
                      )}
                    </div>
                    <StatusBadge status={topic.difficulty} />
                  </div>
                </Link>
              ))}
            </div>
          )
        })
      )}
    </div>
  )
}
