'use client';
import * as React from 'react';
import { ChevronRight } from 'lucide-react';
import { LogoWrapper } from '@/components/LogoWrapper';
import { NavUser } from '@/components/nav-user';
import {
  filterMenuItems,
  menuItems,
  type MenuItem,
} from '@/config/menu.config';
import { usePermissions } from '@/hooks/usePermissions';
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from '@/components/ui/collapsible';
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarMenuSub,
  SidebarMenuSubButton,
  SidebarMenuSubItem,
  SidebarRail,
  SidebarTrigger,
  useSidebar,
} from '@/components/ui/sidebar';
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from '@/components/ui/tooltip';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useAppStore } from '@/store/app.store';

function isRouteActive(pathname: string, path?: string) {
  if (!path) return false;
  return pathname === path || pathname.startsWith(`${path}/`);
}

export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
  const pathname = usePathname();
  const { hasPermission } = usePermissions();
  const { isMobile } = useSidebar();
  const authUser = useAppStore((state) => state.user);
  const navItems = filterMenuItems(menuItems, hasPermission);
  const user = {
    name:
      [authUser?.first_name, authUser?.last_name].filter(Boolean).join(' ') ||
      'Admin',
    email: authUser?.email || '',
    avatar: authUser?.profile_photo_url || '/avatars/profile.jpg',
  };

  return (
    <Sidebar collapsible="icon" {...props}>
      <SidebarHeader className="border-b border-sidebar-border px-3 py-3 group-data-[collapsible=icon]:items-center group-data-[collapsible=icon]:border-b-0 group-data-[collapsible=icon]:px-2">
        <div className="flex h-8 w-full items-center gap-3 group-data-[collapsible=icon]:w-8 group-data-[collapsible=icon]:justify-center">
          <SidebarBrandControl isMobile={isMobile} />
          <div className="grid flex-1 text-left text-sm leading-tight group-data-[collapsible=icon]:hidden">
            <span className="truncate font-semibold">RoadMonitor</span>
            <span className="truncate text-xs">Road Intelligence</span>
          </div>
          <SidebarTrigger
            className="ml-auto shrink-0 bg-sidebar/80 text-sidebar-foreground/80 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:hidden"
            aria-label={isMobile ? 'Close menu' : 'Hide menu'}
          />
        </div>
      </SidebarHeader>
      <SidebarContent className="px-2 py-3">
        <SidebarGroup className="p-0">
          <SidebarMenu>
            {navItems.map((item) => (
              <SidebarNavItem
                key={item.title}
                item={item}
                pathname={pathname}
              />
            ))}
          </SidebarMenu>
        </SidebarGroup>
      </SidebarContent>
      <SidebarFooter className="border-t border-sidebar-border px-3 py-3">
        <NavUser user={user} />
      </SidebarFooter>
      <SidebarRail />
    </Sidebar>
  );
}

function SidebarBrandControl({ isMobile }: { isMobile: boolean }) {
  return (
    <div className="group/sidebar-brand relative flex size-8 shrink-0 items-center justify-center">
      <LogoWrapper
        size="sm"
        variant="sidebar"
        className="transition-opacity duration-150 group-data-[collapsible=icon]:group-hover/sidebar-brand:opacity-0 group-data-[collapsible=icon]:group-focus-within/sidebar-brand:opacity-0"
      />
      <Tooltip>
        <TooltipTrigger asChild>
          <SidebarTrigger
            className="pointer-events-none absolute inset-0 bg-sidebar text-sidebar-foreground/80 opacity-0 shadow-none hover:bg-sidebar-accent hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:pointer-events-auto group-data-[collapsible=icon]:group-hover/sidebar-brand:opacity-100 group-data-[collapsible=icon]:group-focus-within/sidebar-brand:opacity-100"
            aria-label={isMobile ? 'Close menu' : 'Open menu'}
          />
        </TooltipTrigger>
        <TooltipContent side="right">Open menu</TooltipContent>
      </Tooltip>
    </div>
  );
}

function SidebarNavItem({
  item,
  pathname,
}: {
  item: MenuItem;
  pathname: string;
}) {
  const isActive = isRouteActive(pathname, item.path);
  const isChildActive =
    item.children?.some((child) => isRouteActive(pathname, child.path)) ??
    false;
  const hasChildren = Boolean(item.children?.length);
  const [open, setOpen] = React.useState(isChildActive);

  React.useEffect(() => {
    if (isChildActive) setOpen(true);
  }, [isChildActive]);

  if (hasChildren) {
    return (
      <Collapsible
        asChild
        open={open}
        onOpenChange={setOpen}
        className="group/collapsible"
      >
        <SidebarMenuItem>
          <CollapsibleTrigger asChild>
            <SidebarMenuButton tooltip={item.title} isActive={isChildActive}>
              <item.icon />
              <span>{item.title}</span>
              <ChevronRight className="ml-auto transition-transform duration-200 group-data-[state=open]/collapsible:rotate-90" />
            </SidebarMenuButton>
          </CollapsibleTrigger>
          <CollapsibleContent>
            <SidebarMenuSub>
              {item.children?.map((child) => (
                <SidebarMenuSubItem key={child.title}>
                  {child.path ? (
                    <SidebarMenuSubButton
                      asChild
                      isActive={isRouteActive(pathname, child.path)}
                    >
                      <Link href={child.path}>
                        <child.icon />
                        <span>{child.title}</span>
                      </Link>
                    </SidebarMenuSubButton>
                  ) : null}
                </SidebarMenuSubItem>
              ))}
            </SidebarMenuSub>
          </CollapsibleContent>
        </SidebarMenuItem>
      </Collapsible>
    );
  }

  return (
    <SidebarMenuItem>
      {item.path ? (
        <SidebarMenuButton asChild tooltip={item.title} isActive={isActive}>
          <Link href={item.path}>
            <item.icon />
            <span>{item.title}</span>
          </Link>
        </SidebarMenuButton>
      ) : (
        <SidebarMenuButton tooltip={item.title} isActive={isChildActive}>
          <item.icon />
          <span>{item.title}</span>
        </SidebarMenuButton>
      )}
    </SidebarMenuItem>
  );
}
