'use client'

import { ReactNode, useState, useRef, useEffect } from 'react'
import { CaretRight } from '@phosphor-icons/react'
import { cn } from '@/lib/utils'

interface SidebarGroupProps {
  title: ReactNode
  children: ReactNode
  defaultOpen?: boolean
  selected?: boolean
  indent?: number
  onClick?: () => void
  asideContent?: ReactNode
  /** Selected child slug - when this changes and a child is selected, auto-expand */
  selectedChildSlug?: string | null
}

/**
 * Sidebar Group component - collapsible group with toggle
 * Arrow on right side with smooth rotation and expand animations
 */
export function SidebarGroup({
  title,
  children,
  defaultOpen = false,
  selected = false,
  indent = 0,
  onClick,
  asideContent,
  selectedChildSlug,
}: SidebarGroupProps) {
  const [isOpen, setIsOpen] = useState(defaultOpen)
  const contentRef = useRef<HTMLUListElement>(null)
  const [contentHeight, setContentHeight] = useState<number | undefined>(
    defaultOpen ? undefined : 0
  )

  // Auto-expand when a child is selected (e.g., via agent navigation)
  // Triggers on defaultOpen change OR when selectedChildSlug changes (even if defaultOpen stays true)
  useEffect(() => {
    if (defaultOpen) {
      setIsOpen(true)
    }
  }, [defaultOpen, selectedChildSlug])

  // Update height when open state changes
  useEffect(() => {
    if (isOpen) {
      const height = contentRef.current?.scrollHeight
      setContentHeight(height)
      // After animation, set to auto for dynamic content
      const timer = setTimeout(() => setContentHeight(undefined), 200)
      return () => clearTimeout(timer)
    } else {
      // First set the current height, then animate to 0
      const height = contentRef.current?.scrollHeight
      setContentHeight(height)
      requestAnimationFrame(() => {
        setContentHeight(0)
      })
    }
  }, [isOpen])

  const handleToggle = () => {
    setIsOpen(!isOpen)
    onClick?.()
  }

  return (
    <li className="docs-sidebar-group flex flex-col">
      <button
        type="button"
        aria-expanded={isOpen}
        onClick={handleToggle}
        className={cn(
          // Base styles
          'docs-sidebar-group-toggle group/button flex items-center rounded-lg px-3 py-2 w-full text-left',
          'text-sm leading-5 transition-colors duration-150',
          // State variants
          selected
            ? 'docs-sidebar-group-active bg-sidebar-primary text-sidebar-primary-foreground font-medium'
            : 'text-sidebar-foreground/80 hover:bg-sidebar-accent/30 hover:text-sidebar-foreground'
        )}
        style={{ paddingLeft: indent > 0 ? `${indent * 12 + 12}px` : undefined }}
      >
        <span className="flex-1 truncate font-medium">{title}</span>
        {asideContent && (
          <span className="ml-2 shrink-0">{asideContent}</span>
        )}
        {/* Toggle icon - right side with rotation animation */}
        <span className="docs-sidebar-group-icon ml-2 text-sidebar-foreground/50 group-hover/button:text-sidebar-foreground/70">
          <CaretRight 
            weight="bold" 
            className={cn(
              "h-3.5 w-3.5 transition-transform duration-200 ease-out",
              isOpen && "rotate-90"
            )}
          />
        </span>
      </button>
      {/* Child items with expand animation */}
      <ul 
        ref={contentRef}
        className={cn(
          "docs-sidebar-group-items flex flex-col overflow-hidden transition-all duration-200 ease-out",
          !isOpen && "opacity-0",
          isOpen && "opacity-100"
        )}
        style={{ 
          height: contentHeight !== undefined ? `${contentHeight}px` : 'auto',
        }}
      >
        {children}
      </ul>
    </li>
  )
}
