import { forwardRef, useState } from 'react'
import type { HTMLAttributes, ReactNode } from 'react'
import { cn } from '@/lib/utils'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from './dropdown-menu'
import { MoreLine } from './icons-inline'

export interface SidebarMenuItemAction {
  id: string
  label: string
  icon?: ReactNode
  onClick?: () => void
  destructive?: boolean
}

export interface SidebarMenuItem {
  id: string
  label: string
  icon?: ReactNode
  disabled?: boolean
  actions?: SidebarMenuItemAction[]
}

export interface SidebarMenuProps extends HTMLAttributes<HTMLDivElement> {
  items: SidebarMenuItem[]
  selectedId?: string
  onItemClick?: (item: SidebarMenuItem) => void
  width?: string
  moreIcon?: ReactNode
}

const moreClass = 'w-4 h-4'

export const SidebarMenu = forwardRef<HTMLDivElement, SidebarMenuProps>(
  (
    {
      items,
      selectedId,
      onItemClick,
      width = 'w-52',
      className,
      moreIcon,
      ...props
    },
    ref
  ) => {
    const [openDropdownId, setOpenDropdownId] = useState<string | null>(null)
    const baseStyles = 'flex flex-col gap-1.5 rounded-md bg-transparent'
    const defaultMore = moreIcon ?? <MoreLine className={moreClass} />

    return (
      <div ref={ref} className={cn(baseStyles, width, className)} {...props}>
        {items.map((item) => {
          const isSelected = selectedId === item.id
          const isDisabled = item.disabled
          const isOpen = openDropdownId === item.id

          return (
            <div
              key={item.id}
              className={cn(
                'group flex items-center gap-2 py-1 px-2 rounded-md text-sm leading-sm transition-colors',
                'focus-within:outline-none min-w-0',
                isDisabled && 'opacity-50 cursor-not-allowed',
                !isDisabled && 'cursor-pointer',
                isSelected
                  ? 'bg-fill-secondary text-text'
                  : 'bg-transparent text-text-secondary hover:bg-fill-secondary hover:text-text'
              )}
            >
              <button
                onClick={() => {
                  if (!isDisabled) onItemClick?.(item)
                  setOpenDropdownId(null)
                }}
                disabled={isDisabled}
                className="flex-1 text-left truncate min-w-0 rounded-sm outline-none bg-transparent border-none p-0 cursor-pointer focus-visible:ring-2 focus-visible:ring-primary-border"
              >
                {item.label}
              </button>
              {item.actions && item.actions.length > 0 ? (
                <div onClick={(e) => e.stopPropagation()}>
                  <DropdownMenu
                    open={isOpen}
                    onOpenChange={(open) => {
                      setOpenDropdownId(open ? item.id : null)
                    }}
                  >
                    <DropdownMenuTrigger asChild>
                      <button
                        className={cn(
                          'flex items-center justify-center p-1 rounded outline-none transition-all duration-200 relative z-10 cursor-pointer hover:bg-fill-primary focus-visible:ring-2 focus-visible:ring-primary-border'
                        )}
                        style={{ pointerEvents: 'auto' }}
                        onClick={(e) => e.stopPropagation()}
                        onMouseDown={(e) => e.stopPropagation()}
                      >
                        <span
                          className={cn(
                            'transition-opacity pointer-events-none flex items-center justify-center',
                            isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
                          )}
                        >
                          {item.icon ?? (
                            <span
                              className={cn(
                                'w-4 h-4 inline-flex items-center justify-center',
                                isSelected ? 'text-text' : 'text-text-secondary'
                              )}
                            >
                              {defaultMore}
                            </span>
                          )}
                        </span>
                      </button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                      {item.actions.map((action) => (
                        <DropdownMenuItem
                          key={action.id}
                          variant={action.destructive ? 'destructive' : 'default'}
                          onClick={(e) => {
                            e.stopPropagation()
                            setOpenDropdownId(null)
                            action.onClick?.()
                          }}
                        >
                          {action.icon && (
                            <span className="mr-2 w-4 h-4 flex items-center justify-center">
                              {action.icon}
                            </span>
                          )}
                          {action.label}
                        </DropdownMenuItem>
                      ))}
                    </DropdownMenuContent>
                  </DropdownMenu>
                </div>
              ) : (
                <span
                  className="flex-shrink-0 w-4 h-4 flex items-center justify-center"
                  onClick={(e) => e.stopPropagation()}
                >
                  {item.icon ? (
                    <span
                      className={cn(
                        'transition-opacity pointer-events-none',
                        isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
                      )}
                    >
                      {item.icon}
                    </span>
                  ) : (
                    <span
                      className={cn(
                        'w-4 h-4 inline-flex items-center justify-center transition-opacity pointer-events-none',
                        isSelected ? 'opacity-100 text-text' : 'opacity-0 group-hover:opacity-100 text-text-secondary'
                      )}
                    >
                      {defaultMore}
                    </span>
                  )}
                </span>
              )}
            </div>
          )
        })}
      </div>
    )
  }
)

SidebarMenu.displayName = 'SidebarMenu'
