import { useState, type ReactNode } from 'react'
import { cn } from '@/lib/utils'

interface CollapsibleSectionProps {
  title: string
  subtitle?: string
  defaultOpen?: boolean
  headerRight?: ReactNode
  onToggle?: (open: boolean) => void
  children: ReactNode
}

export function CollapsibleSection({ title, subtitle, defaultOpen = true, headerRight, onToggle, children }: CollapsibleSectionProps) {
  const [open, setOpen] = useState(defaultOpen)

  return (
    <div className="rounded-lg border bg-card">
      <button
        className="flex w-full items-center justify-between p-4 text-left"
        onClick={() => { const next = !open; setOpen(next); onToggle?.(next) }}
      >
        <div className="flex items-center gap-2">
          <span className={cn('text-sm font-bold transition-transform', open ? 'rotate-90' : 'rotate-0')}>▶</span>
          <div>
            <h2 className="text-sm font-bold">{title}</h2>
            {subtitle && <p className="text-xs text-muted-foreground">{subtitle}</p>}
          </div>
        </div>
        {headerRight && <div onClick={(e) => e.stopPropagation()}>{headerRight}</div>}
      </button>
      {open && <div className="border-t px-4 pb-4 pt-3">{children}</div>}
    </div>
  )
}
