import { useState, useId, type ReactNode } from 'react'
import { ChevronRight } from 'lucide-react'
import { cn } from '@/lib/utils'

interface CollapsibleEditorSectionProps {
  title: string
  icon: ReactNode
  summary: string
  expanded?: boolean
  onToggle?: () => void
  defaultExpanded?: boolean
  children: ReactNode
}

export function CollapsibleEditorSection({
  title,
  icon,
  summary,
  expanded: controlledExpanded,
  onToggle,
  defaultExpanded = false,
  children,
}: CollapsibleEditorSectionProps) {
  const [internalExpanded, setInternalExpanded] = useState(defaultExpanded)
  const isExpanded = controlledExpanded ?? internalExpanded
  const generatedId = useId()
  const sectionId = `section-${generatedId}`

  const handleToggle = () => {
    if (onToggle) {
      onToggle()
    } else {
      setInternalExpanded(!internalExpanded)
    }
  }

  return (
    <div className="border-b border-border">
      <button
        type="button"
        onClick={handleToggle}
        aria-expanded={isExpanded}
        aria-controls={sectionId}
        className="flex w-full items-center gap-3 px-4 py-2.5 text-left transition-colors hover:bg-accent/50"
      >
        <ChevronRight
          className={cn(
            'h-4 w-4 shrink-0 text-muted-foreground transition-transform duration-200',
            isExpanded && 'rotate-90'
          )}
        />
        <span className="shrink-0 text-muted-foreground">{icon}</span>
        <span className="text-sm font-medium text-foreground">{title}</span>
        {!isExpanded && (
          <span className="min-w-0 truncate text-sm text-muted-foreground">
            — {summary}
          </span>
        )}
      </button>

      {isExpanded && (
        <div id={sectionId} className="px-4 pb-4 pt-1">
          {children}
        </div>
      )}
    </div>
  )
}
