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

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

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

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

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

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

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

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

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

          <span className='text-base'>{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>
      {menu.map((menuItem, menuIdx) => (
        <SidebarMenuItem
          key={menuIdx}
          item={menuItem}
          activeLink={activeLink}
        />
      ))}
    </Menu>
  );
};

export default SidebarMenu;
