import Link from 'next/link';
import Menu from '@/components/menu/Menu';
import { Icon } from '@iconify/react';
import { cn, isPathActive } from '@/lib/helper';
import { useAuth } from '@/services/hooks/useAuth';

export interface SidebarMenuItem {
  type?: 'item' | 'title';
  text: string;
  link: string;
  icon?: string;
  submenu?: SidebarMenuItem[];
  permission?: string[];
}

interface SidebarMenuItemProps {
  item: SidebarMenuItem;
  activeLink: string;
}

interface SidebarMenuProps {
  menu: SidebarMenuItem[];
  activeLink: string;
}

const SidebarMenuItem = ({ item, activeLink }: SidebarMenuItemProps) => {
  const { permissionCheck } = useAuth();
  const isItemActive = isPathActive(activeLink, item.link);

  const isUserPermitted = item.permission
    ? item.permission?.some((permissionName) => permissionCheck(permissionName))
    : true;

  if (!isUserPermitted) {
    return null;
  }

  const menuItemWithoutSubmenu = (
    <li>
      <Link
        href={item.link}
        className={cn('px-3 py-1.5', {
          'text-base-content/60': !isItemActive,
          'menu-active border-[1.5px] border-solid border-base-300':
            isItemActive,
        })}
      >
        {item.icon && <Icon icon={item.icon} width={20} height={20} />}

        <span className='text-sm'>{item.text}</span>
      </Link>
    </li>
  );

  if (!item.submenu || item.submenu.length === 0) {
    return menuItemWithoutSubmenu;
  }

  const menuItemWithSubmenu = (
    <li>
      <details open={isItemActive}>
        <summary
          className={cn({
            'text-base-content/60': !isItemActive,
            'text-primary': isItemActive,
          })}
        >
          {item.icon && <Icon icon={item.icon} width={20} height={20} />}

          <span className='text-sm'>{item.text}</span>
        </summary>

        <ul>
          {item.submenu.map((submenuItem, submenuIdx) => (
            <SidebarMenuItem
              key={`submenu#${submenuIdx}`}
              item={submenuItem}
              activeLink={activeLink}
            />
          ))}
        </ul>
      </details>
    </li>
  );

  return menuItemWithSubmenu;
};

const SidebarMenu = ({ menu, activeLink }: SidebarMenuProps) => {
  return (
    <Menu className='p-3'>
      {menu.map((menuItem, menuIdx) => {
        return (
          <SidebarMenuItem
            key={menuIdx}
            item={menuItem}
            activeLink={activeLink}
          />
        );
      })}
    </Menu>
  );
};

export default SidebarMenu;
