'use client';
import * as React from 'react';
import { ChevronRight, Package } from 'lucide-react';
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,
  SidebarHeader,
  SidebarRail,
  SidebarMenu,
  SidebarMenuItem,
  SidebarMenuButton,
  SidebarMenuSub,
  SidebarMenuSubButton,
  SidebarMenuSubItem,
  SidebarGroup,
  SidebarGroupLabel,
} from '@/components/ui/sidebar';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useAppStore } from '@/store/app.store';

export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
  const pathname = usePathname();
  const { hasPermission } = usePermissions();
  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>
        <div className="flex items-center gap-2 py-2">
          <div className="flex aspect-square size-8 items-center justify-center rounded-lg bg-primary text-primary-foreground">
            <Package className="size-4" />
          </div>
          <div className="grid flex-1 text-left text-sm leading-tight group-data-[collapsible=icon]:hidden">
            <span className="truncate font-semibold">Vision Road</span>
            <span className="truncate text-xs">Analytics Platform</span>
          </div>
        </div>
      </SidebarHeader>
      <SidebarContent>
        <SidebarGroup>
          <SidebarMenu>
            {navItems.map((item) => (
              <SidebarNavItem
                key={item.title}
                item={item}
                pathname={pathname}
              />
            ))}
          </SidebarMenu>
        </SidebarGroup>
      </SidebarContent>
      <SidebarFooter>
        <NavUser user={user} />
      </SidebarFooter>
      <SidebarRail />
    </Sidebar>
  );
}

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

  if (hasChildren) {
    return (
      <Collapsible
        asChild
        defaultOpen={isChildActive}
        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={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>
  );
}
