import { ChevronDownIcon, ChevronLeftIcon, ChevronRightIcon } from '@radix-ui/react-icons'

import * as React from 'react'

import { cn } from '@lib/utils'

// Context for sidebar state
type SidebarContextValue = {
  isOpen: boolean
  setIsOpen: (open: boolean) => void
  isCollapsed: boolean
  setIsCollapsed: (collapsed: boolean) => void
}

const SidebarContext = React.createContext<SidebarContextValue | null>(null)

function useSidebar() {
  const context = React.useContext(SidebarContext)
  if (!context) {
    throw new Error('useSidebar must be used within a SidebarProvider')
  }
  return context
}

// Provider
type SidebarProviderProps = {
  children: React.ReactNode
  defaultOpen?: boolean
  defaultCollapsed?: boolean
}

function SidebarProvider({ children, defaultOpen = false, defaultCollapsed = false }: SidebarProviderProps) {
  const [isOpen, setIsOpen] = React.useState(defaultOpen)
  const [isCollapsed, setIsCollapsed] = React.useState(defaultCollapsed)

  return (
    <SidebarContext.Provider value={{ isOpen, setIsOpen, isCollapsed, setIsCollapsed }}>
      {children}
    </SidebarContext.Provider>
  )
}

// Root sidebar container
type SidebarProps = React.HTMLAttributes<HTMLElement> & {
  children: React.ReactNode
}

function Sidebar({ children, className, ...props }: SidebarProps) {
  const { isOpen, isCollapsed } = useSidebar()

  return (
    <aside
      className={cn(
        'fixed md:sticky top-0 left-0 h-screen bg-white dark:bg-gray-900 border-r border-gray-200 dark:border-gray-700',
        'overflow-y-auto transition-all duration-300 z-40',
        isOpen ? 'translate-x-0' : '-translate-x-full md:translate-x-0',
        isCollapsed ? 'w-16 min-w-16' : 'w-64 min-w-64',
        className,
      )}
      {...props}
    >
      {children}
    </aside>
  )
}

// Mobile toggle button
type SidebarMobileToggleProps = React.ButtonHTMLAttributes<HTMLButtonElement>

function SidebarMobileToggle({ className, ...props }: SidebarMobileToggleProps) {
  const { isOpen, setIsOpen } = useSidebar()

  return (
    <button
      onClick={() => setIsOpen(!isOpen)}
      className={cn(
        'fixed top-4 left-4 z-50 md:hidden p-2 bg-white dark:bg-gray-900 rounded shadow-lg border border-gray-200 dark:border-gray-700',
        className,
      )}
      aria-label="Toggle menu"
      {...props}
    >
      {isOpen ? <ChevronDownIcon className="w-6 h-6" /> : <ChevronRightIcon className="w-6 h-6" />}
    </button>
  )
}

// Mobile overlay
type SidebarOverlayProps = React.HTMLAttributes<HTMLDivElement>

function SidebarOverlay({ className, ...props }: SidebarOverlayProps) {
  const { isOpen, setIsOpen } = useSidebar()

  if (!isOpen) return null

  return (
    <div
      className={cn('fixed inset-0 bg-black/20 z-30 md:hidden', className)}
      onClick={() => setIsOpen(false)}
      {...props}
    />
  )
}

// Header with title and collapse toggle
type SidebarHeaderProps = Omit<React.HTMLAttributes<HTMLDivElement>, 'title'> & {
  title?: React.ReactNode
  showCollapseToggle?: boolean
}

function SidebarHeader({ title, showCollapseToggle = true, className, children, ...props }: SidebarHeaderProps) {
  const { isCollapsed, setIsCollapsed } = useSidebar()

  return (
    <div className={cn('flex items-center justify-between mb-4', className)} {...props}>
      {!isCollapsed && (title || children)}
      {showCollapseToggle && (
        <button
          onClick={() => setIsCollapsed(!isCollapsed)}
          className="hidden md:block p-1 hover:bg-gray-100 dark:hover:bg-gray-800 rounded transition-colors ml-auto"
          aria-label={isCollapsed ? 'Expand sidebar' : 'Collapse sidebar'}
        >
          {isCollapsed ? <ChevronRightIcon className="w-5 h-5" /> : <ChevronLeftIcon className="w-5 h-5" />}
        </button>
      )}
    </div>
  )
}

// Content container (hidden when collapsed)
type SidebarContentProps = React.HTMLAttributes<HTMLDivElement>

function SidebarContent({ className, children, ...props }: SidebarContentProps) {
  const { isCollapsed } = useSidebar()

  if (isCollapsed) return null

  return (
    <nav className={className} {...props}>
      {children}
    </nav>
  )
}

// Collapsible section
type SidebarSectionProps = {
  title: string
  defaultExpanded?: boolean
  children: React.ReactNode
  className?: string
}

function SidebarSection({ title, defaultExpanded = true, children, className }: SidebarSectionProps) {
  const [isExpanded, setIsExpanded] = React.useState(defaultExpanded)

  return (
    <div className={cn('mb-4', className)}>
      <button
        onClick={() => setIsExpanded(!isExpanded)}
        className="flex items-center justify-between w-full px-4 py-2 font-semibold text-left hover:bg-gray-100 dark:hover:bg-gray-800 rounded transition-colors"
      >
        <span>{title}</span>
        {isExpanded ? <ChevronDownIcon className="w-4 h-4" /> : <ChevronRightIcon className="w-4 h-4" />}
      </button>
      {isExpanded && <ul className="mt-2 ml-2 space-y-1">{children}</ul>}
    </div>
  )
}

// Individual navigation item
type SidebarItemProps = {
  children: React.ReactNode
  className?: string
}

function SidebarItem({ children, className }: SidebarItemProps) {
  return <li className={cn('', className)}>{children}</li>
}

// Link styling helper
const sidebarLinkClassName = 'block px-4 py-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded transition-colors'

export {
  Sidebar,
  SidebarContent,
  SidebarHeader,
  SidebarItem,
  sidebarLinkClassName,
  SidebarMobileToggle,
  SidebarOverlay,
  SidebarProvider,
  SidebarSection,
  useSidebar,
}
