import React from 'react'
import { MenuAsideItem } from '../interfaces'
import AsideMenuItem from './AsideMenuItem'
import { useAppSelector } from '../stores/hooks';
import { hasPermission } from '../helpers/userPermissions';
import { getWorkspaceConfig, getWorkspaceRoute, itemVisibleForRole } from '../helpers/workspace';

type Props = {
  menu: MenuAsideItem[]
  isDropdownList?: boolean
  className?: string
}

export default function AsideMenuList({ menu, isDropdownList = false, className = '' }: Props) {
  const { currentUser } = useAppSelector((state) => state.auth);

  if (!currentUser) return null;

  const roleName = currentUser?.app_role?.name;
  const workspaceConfig = getWorkspaceConfig(roleName);

  return (
    <ul className={className}>
      {menu.map((item, index) => {
        if (!itemVisibleForRole(item.roles, roleName)) return null;
        if (!hasPermission(currentUser, item.permissions)) return null;

        const displayItem: MenuAsideItem = {
          ...item,
          label: item.labelByRole?.[roleName] || item.label,
        };

        if (displayItem.label === 'Role Workspace') {
          displayItem.label = workspaceConfig.sidebarLabel;
          displayItem.href = getWorkspaceRoute(roleName);
        }

        return (
          <div key={index}>
            <AsideMenuItem
              item={displayItem}
              isDropdownList={isDropdownList}
            />
          </div>
        )
      })}
    </ul>
  )
}
