import { useState } from 'react'
import { ChevronDown, ChevronUp } from 'lucide-react'
import { cn } from '@/lib/utils'

interface CategoryItem {
  id: string
  name: string
  color: string
  count: number
}

interface CategoryListProps {
  categories: CategoryItem[]
  activeId?: string | null
  onSelect: (id: string | null) => void
}

const VISIBLE_COUNT = 4

export function CategoryList({ categories, activeId, onSelect }: CategoryListProps) {
  const [expanded, setExpanded] = useState(false)

  if (categories.length === 0) return null

  const hasMore = categories.length > VISIBLE_COUNT
  const visible = expanded ? categories : categories.slice(0, VISIBLE_COUNT)

  return (
    <div className="px-3 py-2">
      <p className="mb-2 px-3 font-heading text-[0.6875rem] font-bold uppercase tracking-[0.04em] text-muted-foreground">
        Categories
      </p>
      <div className="space-y-0.5">
        {visible.map(cat => (
          <button
            key={cat.id}
            onClick={() => onSelect(activeId === cat.id ? null : cat.id)}
            className={cn(
              'flex w-full items-center gap-2.5 rounded-lg px-3 py-1.5 text-sm transition-colors',
              activeId === cat.id
                ? 'bg-[hsl(var(--sidebar-active))] text-foreground'
                : 'text-muted-foreground hover:bg-[hsl(var(--sidebar-hover))] hover:text-foreground'
            )}
          >
            <span
              className="h-2 w-2 shrink-0 rounded-full"
              style={{ backgroundColor: cat.color }}
            />
            <span className="flex-1 truncate text-left">{cat.name}</span>
            <span className="font-label text-[0.6875rem] text-[hsl(var(--text-dimmed))]">{cat.count}</span>
          </button>
        ))}
        {hasMore && (
          <button
            onClick={() => setExpanded(v => !v)}
            className="flex w-full items-center gap-2.5 rounded-lg px-3 py-1.5 text-[0.8125rem] text-muted-foreground hover:bg-[hsl(var(--sidebar-hover))] hover:text-foreground transition-colors"
          >
            {expanded ? (
              <>
                <ChevronUp className="h-3.5 w-3.5" />
                <span>Show less</span>
              </>
            ) : (
              <>
                <ChevronDown className="h-3.5 w-3.5" />
                <span>{categories.length - VISIBLE_COUNT} more</span>
              </>
            )}
          </button>
        )}
      </div>
    </div>
  )
}
