import { Link } from "react-router-dom"
import { ChevronRight } from "lucide-react"
import {
  Sidebar,
  SidebarContent,

  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarMenuSub,
  SidebarMenuSubItem,
  SidebarMenuSubButton,
  SidebarGroup,
  SidebarGroupLabel,
  SidebarGroupContent,
  SidebarRail,
  useSidebar,
} from "@/components/ui/sidebar"
import { useNavigation, type NavItem } from "@/contexts/navigation-context"

import { cn } from "@/lib/utils"
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { useSocket } from "@/hooks/use-socket"

function NavItemWithSubMenu({ item }: { item: NavItem }) {
  const { state } = useSidebar()
  const isCollapsed = state === "collapsed"

  // When collapsed, show a dropdown menu on hover/click
  if (isCollapsed) {
    return (
      <SidebarMenuItem>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <SidebarMenuButton
              tooltip={item.title}
              className={cn(
                "transition-all duration-200 ease-in-out font-medium py-4 min-h-10",
                item.isActive 
                  ? "bg-primary/10 text-primary shadow-[inset_4px_0_0_0_hsl(var(--primary))] hover:bg-primary/15 hover:text-primary" 
                  : "text-muted-foreground hover:text-foreground hover:bg-white/5"
              )}
            >
              <item.icon className={cn("size-5", item.isActive && "text-primary fill-primary/20")} />
            </SidebarMenuButton>
          </DropdownMenuTrigger>
          <DropdownMenuContent
            side="right"
            align="start"
            sideOffset={8}
            className="min-w-[180px] bg-background/95 backdrop-blur-xl border-border/50"
          >
            <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
              {item.title}
            </div>
              {item.subItems?.map((subItem) => (
              <DropdownMenuItem key={subItem.title} asChild className="group/dropitem">
                <Link 
                  to={subItem.url}
                  className={cn(
                    "cursor-pointer py-4 min-h-10 flex items-center gap-2",
                    subItem.isActive 
                      ? "text-primary bg-primary/10" 
                      : "text-muted-foreground hover:text-inherit"
                  )}
                >
                  <subItem.icon className={cn("size-4", subItem.isActive ? "text-primary" : "text-muted-foreground group-hover/dropitem:text-inherit")} />
                  {subItem.title}
                </Link>
              </DropdownMenuItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>
      </SidebarMenuItem>
    )
  }

  // When expanded, show collapsible sub-menu
  return (
    <Collapsible defaultOpen={item.isActive} className="group/collapsible">
      <SidebarMenuItem className="flex flex-col">
        <CollapsibleTrigger asChild>
          <SidebarMenuButton
              tooltip={item.title}
              className={cn(
                "transition-all duration-200 ease-in-out font-medium py-4 min-h-10",
                item.isActive 
                  ? "bg-primary/10 text-primary shadow-[inset_4px_0_0_0_hsl(var(--primary))] hover:bg-primary/15 hover:text-primary" 
                  : "text-muted-foreground hover:text-foreground hover:bg-white/5"
              )}
            >
              <item.icon className={cn("size-5", item.isActive && "text-primary fill-primary/20")} />
              <span className={cn("group-data-[collapsible=icon]:hidden", item.isActive && "text-primary")}>
                {item.title}
              </span>
              <ChevronRight className="ml-auto size-4 transition-transform duration-200 group-data-[state=open]/collapsible:rotate-90 group-data-[collapsible=icon]:hidden" />
            </SidebarMenuButton>
        </CollapsibleTrigger>
        <CollapsibleContent className="overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down">
          <SidebarMenuSub>
            {item.subItems?.map((subItem) => (
              <SidebarMenuSubItem key={subItem.title}>
                <SidebarMenuSubButton
                  asChild
                  isActive={subItem.isActive}
                  className={cn(
                    "transition-all duration-200 py-4 min-h-10 group/subitem",
                    subItem.isActive 
                      ? "text-primary bg-primary/10" 
                      : "text-muted-foreground hover:text-inherit"
                  )}
                >
                  <Link to={subItem.url}>
                    <subItem.icon className={cn("size-4", subItem.isActive ? "text-primary" : "text-muted-foreground group-hover/subitem:text-inherit")} />
                    <span>{subItem.title}</span>
                  </Link>
                </SidebarMenuSubButton>
              </SidebarMenuSubItem>
            ))}
          </SidebarMenuSub>
        </CollapsibleContent>
      </SidebarMenuItem>
    </Collapsible>
  )
}

function NavItemLink({ item }: { item: NavItem }) {
  return (
    <SidebarMenuItem>
      <SidebarMenuButton
        asChild
        isActive={item.isActive}
        tooltip={item.title}
        className={cn(
          "transition-all duration-200 ease-in-out font-medium",
          item.isActive 
            ? "bg-primary/10 text-primary shadow-[inset_4px_0_0_0_hsl(var(--primary))] hover:bg-primary/15 hover:text-primary" 
            : "text-muted-foreground hover:text-foreground hover:bg-white/5"
        )}
      >
        <Link to={item.url} className="flex items-center gap-3 py-4 min-h-10 group-data-[collapsible=icon]:justify-center">
          <item.icon className={cn("size-5", item.isActive && "text-primary fill-primary/20")} />
          <span className={cn("group-data-[collapsible=icon]:hidden", item.isActive && "text-primary")}>{item.title}</span>
        </Link>
      </SidebarMenuButton>
    </SidebarMenuItem>
  )
}

export function AppSidebar() {
  const { navItems } = useNavigation()
  const { stats } = useSocket()
  
  return (
    <Sidebar collapsible="icon" className="border-r border-border/50 bg-background/60 backdrop-blur-xl supports-backdrop-filter:bg-background/60">
      <SidebarHeader className="pb-4 pt-4">
        <SidebarMenu>
          <SidebarMenuItem>
            <SidebarMenuButton size="lg" asChild className="hover:bg-primary/10 transition-colors">
              <Link to="/">
                {stats?.bot?.avatarUrl ? (
                  <img 
                    src={stats.bot.avatarUrl} 
                    alt={stats.bot.name}
                    className="size-10 rounded-full group-data-[collapsible=icon]:size-8 object-cover shadow-lg" 
                  />
                ) : (
                  <div className="flex aspect-square size-10 items-center justify-center rounded-full bg-aurora sun-flare shadow-lg group-data-[collapsible=icon]:size-8">
                    <span className="sr-only">Aurora</span>
                  </div>
                )}
                <div className="grid flex-1 text-left text-sm leading-tight ml-2 group-data-[collapsible=icon]:hidden">
                  <span className="truncate font-bold text-primary text-base">Aurora</span>
                  <span className="truncate text-xs text-muted-foreground font-medium">
                    {stats?.bot?.status || "Online"}
                  </span>
                </div>
              </Link>
            </SidebarMenuButton>
          </SidebarMenuItem>
        </SidebarMenu>
      </SidebarHeader>

      <SidebarContent className="px-2 group-data-[collapsible=icon]:px-0">
        <SidebarGroup>
          <SidebarGroupLabel className="text-muted-foreground/70 uppercase tracking-wider text-xs font-bold mb-2 px-2 group-data-[collapsible=icon]:hidden">
            Menu
          </SidebarGroupLabel>
          <SidebarGroupContent>
            <SidebarMenu className="gap-2 group-data-[collapsible=icon]:items-center">
              {navItems.map((item) => (
                item.subItems ? (
                  <NavItemWithSubMenu key={item.title} item={item} />
                ) : (
                  <NavItemLink key={item.title} item={item} />
                )
              ))}
            </SidebarMenu>
          </SidebarGroupContent>
        </SidebarGroup>
      </SidebarContent>



      <SidebarRail />
    </Sidebar>
  )
}

