import { ChevronDown, ChevronRight } from 'lucide-react';

import { Link, usePage } from '@inertiajs/react';

import { Badge } from '@/Components/ui/badge';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/Components/ui/tooltip';
import type { NavGroup, NavItem } from '@/config/navigation';
import { cn } from '@/lib/utils';

function isNavActive(url: string, href: string): boolean {
  const segments = href.split('/').filter(Boolean);
  if (segments.length <= 1) {
    return url === href || url === href + '/';
  }
  return url.startsWith(href);
}

interface SidebarNavGroupProps {
  group: NavGroup;
  collapsed?: boolean;
  isGroupCollapsed?: boolean;
  onGroupToggle?: () => void;
}

export function SidebarNavGroup({
  group,
  collapsed = false,
  isGroupCollapsed = false,
  onGroupToggle,
}: SidebarNavGroupProps) {
  const isCollapsible = onGroupToggle !== undefined;

  return (
    <div className="px-3 py-2">
      {!collapsed &&
        (isCollapsible ? (
          <button
            type="button"
            onClick={onGroupToggle}
            className="mb-1 flex w-full items-center justify-between px-2 py-0.5 text-xs font-medium uppercase tracking-wider text-sidebar-foreground/50 hover:text-sidebar-foreground/80 transition-colors"
            aria-expanded={!isGroupCollapsed}
          >
            <span>{group.label}</span>
            {isGroupCollapsed ? (
              <ChevronRight className="h-3 w-3 shrink-0" />
            ) : (
              <ChevronDown className="h-3 w-3 shrink-0" />
            )}
          </button>
        ) : (
          <h3 className="mb-1 px-2 text-xs font-medium uppercase tracking-wider text-sidebar-foreground/50">
            {group.label}
          </h3>
        ))}
      {!isGroupCollapsed && (
        <nav className="flex flex-col gap-0.5">
          {group.items.map((item) => (
            <SidebarNavItem key={item.href} item={item} collapsed={collapsed} />
          ))}
        </nav>
      )}
    </div>
  );
}

interface SidebarNavItemProps {
  item: NavItem;
  collapsed?: boolean;
}

export function SidebarNavItem({ item, collapsed = false }: SidebarNavItemProps) {
  const { url } = usePage();
  const isActive = isNavActive(url, item.href);
  const Icon = item.icon;
  const isDisabled = item.disabled === true;

  if (isDisabled) {
    const disabledContent = (
      <span
        aria-disabled="true"
        className={cn(
          'flex items-center gap-3 rounded-md px-2 py-2 text-sm font-medium',
          'text-sidebar-foreground/40 cursor-not-allowed',
          collapsed && 'justify-center px-0',
        )}
      >
        <Icon className="h-4 w-4 shrink-0" />
        {!collapsed && <span className="flex-1">{item.label}</span>}
      </span>
    );

    return (
      <Tooltip>
        <TooltipTrigger asChild>{disabledContent}</TooltipTrigger>
        <TooltipContent side="right">
          {item.disabledTooltip ?? `${item.label} is not available`}
        </TooltipContent>
      </Tooltip>
    );
  }

  const linkContent = (
    <Link
      href={item.href}
      aria-current={isActive ? 'page' : undefined}
      className={cn(
        'flex items-center gap-3 rounded-md px-2 py-2 text-sm font-medium transition-colors',
        'hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
        isActive
          ? 'bg-sidebar-accent text-sidebar-accent-foreground'
          : 'text-sidebar-foreground/80',
        collapsed && 'justify-center px-0',
      )}
    >
      <Icon className="h-4 w-4 shrink-0" />
      {!collapsed && (
        <>
          <span className="flex-1">{item.label}</span>
          {item.badge != null && item.badge > 0 && (
            <Badge
              variant="destructive"
              className="ml-auto h-5 min-w-5 px-1.5 text-xs leading-none"
            >
              {item.badge}
            </Badge>
          )}
        </>
      )}
    </Link>
  );

  if (collapsed) {
    return (
      <Tooltip>
        <TooltipTrigger asChild>
          <span className="relative">
            {linkContent}
            {item.badge != null && item.badge > 0 && (
              <span className="absolute -right-0.5 -top-0.5 flex h-3.5 w-3.5 items-center justify-center rounded-full bg-destructive text-[10px] font-bold text-destructive-foreground">
                {item.badge > 9 ? '9+' : item.badge}
              </span>
            )}
          </span>
        </TooltipTrigger>
        <TooltipContent side="right">{item.label}</TooltipContent>
      </Tooltip>
    );
  }

  return linkContent;
}

interface MobileSidebarNavProps {
  groups: NavGroup[];
  onNavigate?: () => void;
}

export function MobileSidebarNav({ groups, onNavigate }: MobileSidebarNavProps) {
  const { url } = usePage();

  return (
    <nav className="flex flex-col gap-1 px-3 py-2">
      {groups.map((group) => (
        <div key={group.label}>
          <h3 className="mb-1 px-2 text-xs font-medium uppercase tracking-wider text-sidebar-foreground/50">
            {group.label}
          </h3>
          {group.items.map((item) => {
            const Icon = item.icon;
            const isActive = isNavActive(url, item.href);
            return (
              <Link
                key={item.href}
                href={item.href}
                onClick={onNavigate}
                aria-current={isActive ? 'page' : undefined}
                className={cn(
                  'flex items-center gap-3 rounded-md px-2 py-2 text-sm font-medium transition-colors',
                  'hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
                  isActive
                    ? 'bg-sidebar-accent text-sidebar-accent-foreground'
                    : 'text-sidebar-foreground/80',
                )}
              >
                <Icon className="h-4 w-4 shrink-0" />
                <span className="flex-1">{item.label}</span>
                {item.badge != null && item.badge > 0 && (
                  <Badge
                    variant="destructive"
                    className="ml-auto h-5 min-w-5 px-1.5 text-xs leading-none"
                  >
                    {item.badge}
                  </Badge>
                )}
              </Link>
            );
          })}
        </div>
      ))}
    </nav>
  );
}
