import {
  SidebarGroup,
  SidebarGroupLabel,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarMenuSub,
  SidebarMenuSubButton,
  SidebarMenuSubItem,
} from '@/components/ui/sidebar';
import { cn } from '@/lib/utils';
import { NavGroup } from '@/types';
import { Link, usePage } from '@inertiajs/react';
import { CaretDownIcon } from '@phosphor-icons/react';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';

function isUrlMatch(currentUrl: string, targetHref: string): boolean {
  if (!targetHref) return false;
  if (!targetHref.includes('?')) return currentUrl === targetHref;

  const [targetPath, targetQuery] = targetHref.split('?');
  const [currentPath, currentQuery] = currentUrl.split('?');
  if (targetPath !== currentPath) return false;

  const targetParams = new URLSearchParams(targetQuery);
  const currentParams = new URLSearchParams(currentQuery ?? '');
  for (const [key, value] of targetParams) {
    if (currentParams.get(key) !== value) return false;
  }
  return true;
}

type NavItemWithSubmenuProps = {
  item: NavGroup['items'][number];
  variant: 'admin' | 'default';
  pageUrl: string;
};

export function NavMain({
  items = [],
  className,
  variant,
}: {
  items: NavGroup[];
  className?: string;
  variant: 'admin' | 'default';
}) {
  const page = usePage();
  const { t } = useTranslation();

  return items.map((group) => (
    <SidebarGroup key={group.id} className={cn('', className)}>
      {group.title && <SidebarGroupLabel>{t(group.title)}</SidebarGroupLabel>}

      <SidebarMenu className="gap-3">
        {group.items.map((item) => {
          const isActive = item.href ? page.url.startsWith(item.href) : false;

          if (item.subMenu?.length) {
            return (
              <NavItemWithSubmenu
                key={item.id}
                item={item}
                variant={variant}
                pageUrl={page.url}
              />
            );
          }

          return (
            <SidebarMenuItem key={item.id}>
              <SidebarMenuButton
                asChild
                variant={variant}
                isActive={isActive}
                tooltip={{ children: item.title }}
              >
                <Link
                  href={item.href}
                  prefetch
                  className="flex items-center gap-2"
                >
                  <div>
                    {item.icon && (
                      <item.icon
                        className="size-[18px]"
                        weight={isActive ? 'fill' : 'bold'}
                      />
                    )}
                  </div>
                  <span data-slot="label">{t(item.title)}</span>
                </Link>
              </SidebarMenuButton>
            </SidebarMenuItem>
          );
        })}
      </SidebarMenu>
    </SidebarGroup>
  ));
}

function NavItemWithSubmenu({
  item,
  variant,
  pageUrl,
}: NavItemWithSubmenuProps) {
  const { t } = useTranslation();
  const hasSub = !!item.subMenu?.length;

  const isAnySubActive = hasSub
    ? item.subMenu!.some((sub) => isUrlMatch(pageUrl, sub.href))
    : false;

  const [open, setOpen] = useState(isAnySubActive);

  return (
    <SidebarMenuItem
      className={`rounded-md ${
        isAnySubActive || open ? 'bg-white/5' : 'bg-transparent'
      }`}
    >
      <SidebarMenuButton
        onClick={() => setOpen((p) => !p)}
        isActive={isAnySubActive || open}
        variant={variant}
        tooltip={{ children: item.title }}
        className="cursor-pointer items-center justify-between"
      >
        <div className="flex items-center gap-2">
          <div>
            {item.icon && (
              <item.icon
                className="size-[18px]"
                weight={isAnySubActive ? 'fill' : 'bold'}
              />
            )}
          </div>
          <span data-slot="label">{t(item.title)}</span>
        </div>

        <CaretDownIcon
          data-slot="caret"
          className={`transition-transform ${open ? 'rotate-180' : 'rotate-0'}`}
        />
      </SidebarMenuButton>

      {open && (
        <SidebarMenuSub className="gap-1">
          {item.subMenu!.map((sub) => {
            const subActive = isUrlMatch(pageUrl, sub.href);

            return (
              <SidebarMenuSubItem key={sub.id}>
                <SidebarMenuSubButton asChild isActive={subActive}>
                  <Link href={sub.href} prefetch className="flex items-center">
                    <div
                      className={`h-3.5 w-3.5 rounded-full border-2 border-primary ${subActive ? 'bg-primary' : 'bg-transparent'}`}
                    />
                    {t(sub.title)}
                  </Link>
                </SidebarMenuSubButton>
              </SidebarMenuSubItem>
            );
          })}
        </SidebarMenuSub>
      )}
    </SidebarMenuItem>
  );
}
