// Lazy load navigation items to improve FCP
import { type FC, Suspense, useEffect, useState } from 'react';
import { useQuery } from 'react-query';
import { useLocation, useNavigate } from 'react-router-dom';

import Backdrop from '@material-hu/mui/Backdrop';
import Box from '@material-hu/mui/Box';
import Drawer from '@material-hu/mui/Drawer';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import useMediaQuery from '@material-hu/mui/useMediaQuery';

import HuSpinner from '@material-hu/components/design-system/ProgressIndicators/Spinner';
import HuSidebar from '@material-hu/components/design-system/Sidebar';
import {
  SIDEBAR_COLLAPSED_WIDTH,
  SIDEBAR_WIDTH,
} from '@material-hu/components/design-system/Sidebar/constants';

import { logEvent } from 'src/config/amplitude';
import { SUB_MENU_WIDTH } from 'src/constants/sidebar';
import { useFeatureFlagChecker } from 'src/contexts/FeatureFlagsContext';
import { useAuth } from 'src/contexts/JWTContext';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import usePermissions from 'src/hooks/usePermissions';
import { useTimeTrackingAccess } from 'src/hooks/useTimeTrackingAccess';
import { postDraftKeys } from 'src/pages/dashboard/communication/DraftsForReview/queries';
import { useMicroloansNavState } from 'src/pages/dashboard/microloans/hooks/useMicroloansNavState';
import { getDraftPermissions } from 'src/services/posts';
import { getWidgetList } from 'src/services/widgets';
import { EventName } from 'src/types/amplitude';
import { type Widget } from 'src/types/widgets';
import { insertIf } from 'src/utils/arrays';
import { lazyRetry } from 'src/utils/lazyRetry';
import {
  hasAllPermissions,
  hasAnyPermissions,
  ROUTE_PERMISSIONS,
  UserPermissions,
} from 'src/utils/permissions';
import { NAVBAR_HEIGHT } from 'src/utils/sidebar';
import { getActiveUrls } from 'src/utils/widgets';

import { widgetKeys } from 'src/components/dashboard/widgets/queries';
import Scrollbar from 'src/components/Scrollbar';

import ShortcutsSubmenu from '../ShortcutsSubmenu';
import NavPeopleExperienceItem from '../sidebar/items/PeopleExperience';
import NavSection from '../sidebar/NavSection';

import SidebarGroupsSubMenu from './components/SidebarGroupsSubMenu';
import useLibrariesSidebarItem from './hooks/useLibrariesSidebarItem';
import { type SidebarItem } from './types';

const NavTimeOffItem = lazyRetry(() => import('../sidebar/items/TimeOff'));
const NavCommunicationItem = lazyRetry(
  () => import('../sidebar/items/Communication'),
);
const NavGroupsItem = lazyRetry(() => import('../sidebar/items/Groups'));
const NavFeedItem = lazyRetry(() => import('../sidebar/items/Feed'));
const NavNewsItem = lazyRetry(() => import('../sidebar/items/News'));
const NavChatsItem = lazyRetry(() => import('../sidebar/items/Chats'));
const NavNemakEventsItem = lazyRetry(
  () => import('../sidebar/items/NemakEvents'),
);
const NavEventsItem = lazyRetry(() => import('../sidebar/items/Events'));
const NavServiceManagementItem = lazyRetry(
  () => import('../sidebar/items/ServiceManagement'),
);
const NavNemakRecognitionsItem = lazyRetry(
  () => import('../sidebar/items/RecognitionsNemak'),
);
const NavAcknowledgementsItem = lazyRetry(
  () => import('../sidebar/items/Acknowledgements'),
);
const NavFormsItem = lazyRetry(() => import('../sidebar/items/Forms'));
const NavBanBajioRequests = lazyRetry(
  () => import('../sidebar/items/BanBajioRequests'),
);
const NavPayrollMobilityAdoItem = lazyRetry(
  () => import('../sidebar/items/PayrollMobilityAdo'),
);
const NavTimeTrackingItem = lazyRetry(
  () => import('../sidebar/items/TimeTracking'),
);
const NavPerformanceItem = lazyRetry(
  () => import('../sidebar/items/Performance'),
);
const NavGoalsItem = lazyRetry(() => import('../sidebar/items/Goals'));
const NavPeopleItem = lazyRetry(() => import('../sidebar/items/People'));
const NavOrgChartItem = lazyRetry(() => import('../sidebar/items/OrgChart'));
const NavFilesItem = lazyRetry(() => import('../sidebar/items/Files'));
const NavScormItem = lazyRetry(() => import('../sidebar/items/Scorm'));
const NavOnBoardingItem = lazyRetry(
  () => import('../sidebar/items/Onboarding'),
);
const NavSurveysItem = lazyRetry(() => import('../sidebar/items/Surveys'));
const NavDocumentsItem = lazyRetry(() => import('../sidebar/items/Documents'));
const NavMarketplaceItem = lazyRetry(
  () => import('../sidebar/items/Marketplace'),
);
const NavMicroloansItem = lazyRetry(
  () => import('../sidebar/items/Microloans'),
);
const NavShortcutItem = lazyRetry(() => import('../sidebar/items/Shortcut'));
const NavShiftsItem = lazyRetry(() => import('../sidebar/items/Shifts'));
const NavClockItem = lazyRetry(() => import('../sidebar/items/Clock'));
const NavLearningsItem = lazyRetry(() => import('../sidebar/items/Learnings'));
const NavEmployeeLifecycleItem = lazyRetry(
  () => import('../sidebar/items/EmployeeLifecycleItem'),
);
const NavTasksItem = lazyRetry(() => import('../sidebar/items/TasksItem'));
const NavSportsPoolItem = lazyRetry(
  () => import('../sidebar/items/SportsPool'),
);

export type DashboardSidebarProps = {
  isCollapsed: boolean;
  onSubMenu?: (newValue: boolean) => void;
  collapseMenu?: () => void;
  isSubMenuOpened?: boolean;
  hidden: boolean;
};

const { VIEW_WIDGET } = UserPermissions;

// Wrapper component to handle lazy loading of navigation items
const LazyNavItem = ({ children }: { children: React.ReactNode }) => (
  <Suspense fallback={<HuSpinner size="small" />}>{children}</Suspense>
);

// Helper function to wrap navigation items with lazy loading
const createNavItem = (Component: any, props: any) => (
  <LazyNavItem>
    <Component {...props} />
  </LazyNavItem>
);

const DashboardSidebar: FC<DashboardSidebarProps> = props => {
  const {
    isCollapsed = false,
    onSubMenu = () => null,
    collapseMenu = () => null,
    isSubMenuOpened = false,
    hidden,
  } = props;

  const HuGoThemeProvider = useHuGoTheme();
  const { permissions } = useAuth();
  const { checkFeatureFlag } = useFeatureFlagChecker();

  const navigate = useNavigate();
  const location = useLocation();

  const theme = useTheme();
  const isDownMd = useMediaQuery(theme.breakpoints.down('md'));

  const [links, setLinks] = useState<Widget[]>([]);
  const [isShortcutActive, setIsShortcutActive] = useState<boolean>(false);
  const [isGroupsActive, setIsGroupsActive] = useState<boolean>(false);
  const [openBackdrop, setOpenBackdrop] = useState<boolean>(false);

  const { canAccessClock, isManager } = useTimeTrackingAccess();
  const microloansNav = useMicroloansNavState();

  const { data: hasDraftPermissions, isLoading } = useQuery(
    postDraftKeys.all({ limit: 1 }),
    ({ pageParam = '' }) =>
      getDraftPermissions({ limit: 1, cursor: pageParam }),
    {
      cacheTime: 0,
      select: res => res.data.items.length > 0,
      onSuccess: res => {
        const isDraftsRoute = window.location.pathname.includes('/drafts');
        if (isDraftsRoute && !res) {
          navigate('/');
        }
      },
    },
  );

  useEffect(() => {
    const openGroupsSubmenu = location.pathname.startsWith('/groups');
    if (!isDownMd) {
      setIsGroupsActive(openGroupsSubmenu);
      onSubMenu(openGroupsSubmenu);
    }
  }, [location]);

  const onSelectGroupItem = () => {
    setOpenBackdrop(false);
    if (isDownMd) {
      collapseMenu();
    }
  };

  const onSelectShortcutIcon = () => {
    setIsGroupsActive(false);
    setIsShortcutActive(true);
    onSubMenu(true);
    setOpenBackdrop(true);
  };

  const onSelectGroupsIcon = () => {
    setIsShortcutActive(false);
    setIsGroupsActive(true);
    onSubMenu(true);
    setOpenBackdrop(true);
  };

  const onSelectShortcutItem = () => {
    if (isDownMd) {
      collapseMenu();
    }
  };

  const onSelectMainItem = () => {
    if (isShortcutActive) {
      setIsShortcutActive(false);
    }
    if (isGroupsActive) {
      setIsGroupsActive(false);
    }
    onSubMenu(false);
    setOpenBackdrop(false);
  };

  const onBackdropClick = () => {
    onSubMenu(false);
    setOpenBackdrop(false);
    setIsShortcutActive(false);
    setIsGroupsActive(false);
  };

  const onBackdropMdClick = () => {
    onSubMenu(false);
    setOpenBackdrop(false);
    setIsShortcutActive(false);
    setIsGroupsActive(false);
    collapseMenu();
  };

  const isActiveSubMenu = isShortcutActive || isGroupsActive;
  const isActiveMainItemOverride = isActiveSubMenu ? false : undefined;

  const librariesSidebarItem = useLibrariesSidebarItem({
    isCollapsed: isCollapsed,
    onClick: onSelectMainItem,
    isActive: isActiveMainItemOverride,
  });

  const sidebarItems: SidebarItem[] = [
    {
      key: 'sportsPool',
      component: (
        <NavSportsPoolItem
          isCollapsed={isCollapsed}
          onClick={onSelectMainItem}
          isActive={isActiveMainItemOverride}
        />
      ),
      // No permissions gate here — NavSportsPoolItem self-gates via /access endpoint
      // TODO: Re-enable once backend returns VIEW_SPORTS_POOL
      requiredPermissions: [],
    },
    {
      key: 'feed',
      component: createNavItem(NavFeedItem, {
        isCollapsed,
        onClick: onSelectMainItem,
        isActive: isActiveMainItemOverride,
      }),
      requiredPermissions: ROUTE_PERMISSIONS.FEED,
    },
    {
      key: 'groups',
      component: createNavItem(NavGroupsItem, {
        isCollapsed,
        onClick: onSelectGroupsIcon,
        isActive: isGroupsActive,
      }),
      requiredPermissions: ROUTE_PERMISSIONS.GROUPS,
    },
    ...insertIf(!isLoading && !!hasDraftPermissions, {
      key: 'communication',
      component: createNavItem(NavCommunicationItem, {
        isCollapsed,
        onClick: onSelectMainItem,
        isActive: isActiveMainItemOverride,
      }),
      requiredPermissions: [],
    }),
    {
      key: 'news',
      component: createNavItem(NavNewsItem, {
        isCollapsed,
        onClick: onSelectMainItem,
        isActive: isActiveMainItemOverride,
      }),
      requiredPermissions: ROUTE_PERMISSIONS.NEWS,
    },
    {
      key: 'chats',
      component: createNavItem(NavChatsItem, {
        isCollapsed,
        onClick: onSelectMainItem,
        isActive: isActiveMainItemOverride,
      }),
      requiredPermissions: [
        ...ROUTE_PERMISSIONS.CHATS,
        ...ROUTE_PERMISSIONS.CONVERSATIONS,
      ],
    },
    librariesSidebarItem,
    {
      key: 'nemakEvents',
      component: createNavItem(NavNemakEventsItem, {
        isCollapsed,
        onClick: onSelectMainItem,
        isActive: isActiveMainItemOverride,
      }),
      requiredPermissions: ROUTE_PERMISSIONS.EVENTS_NEMAK,
    },
    {
      key: 'events',
      component: createNavItem(NavEventsItem, {
        isCollapsed,
        onClick: onSelectMainItem,
        isActive: isActiveMainItemOverride,
      }),
      requiredPermissions: ROUTE_PERMISSIONS.EVENTS,
    },
    {
      key: 'serviceManagement',
      component: createNavItem(NavServiceManagementItem, {
        isCollapsed,
        onClick: onSelectMainItem,
        isActive: isActiveMainItemOverride,
      }),
      requiredPermissions: ROUTE_PERMISSIONS.WORKFLOWS,
    },
    {
      key: 'recognitionsNemak',
      component: createNavItem(NavNemakRecognitionsItem, {
        isCollapsed,
        onClick: onSelectMainItem,
        isActive: isActiveMainItemOverride,
      }),
      requiredPermissions: ROUTE_PERMISSIONS.RECOGNITIONS_NEMAK,
    },
    {
      key: 'aknowledgements',
      component: createNavItem(NavAcknowledgementsItem, {
        isCollapsed,
        onClick: onSelectMainItem,
        isActive: isActiveMainItemOverride,
      }),
      requiredPermissions: ROUTE_PERMISSIONS.USER_ACKNOWLEDGEMENTS,
    },
    {
      key: 'forms',
      component: createNavItem(NavFormsItem, {
        isCollapsed,
        onClick: onSelectMainItem,
        isActive: isActiveMainItemOverride,
      }),
      requiredPermissions: ROUTE_PERMISSIONS.FORMS,
    },
    {
      key: 'banBajioRequests',
      component: createNavItem(NavBanBajioRequests, {
        isCollapsed,
        onClick: onSelectMainItem,
        isActive: isActiveMainItemOverride,
      }),
      // until the backend sends me the permission, we agree to use the FEED's permission
      requiredPermissions: ROUTE_PERMISSIONS.FEED,
    },
    {
      key: 'payrollMobilityAdo',
      component: createNavItem(NavPayrollMobilityAdoItem, {
        isCollapsed,
        onClick: onSelectMainItem,
        isActive: isActiveMainItemOverride,
      }),
      requiredPermissions: ROUTE_PERMISSIONS.PAYROLL_MOBILITY_ADO,
    },
    {
      key: 'microloans',
      component: createNavItem(NavMicroloansItem, {
        isCollapsed,
        onClick: onSelectMainItem,
        isActive: isActiveMainItemOverride,
        navPath: microloansNav.entryPath,
      }),
      requiredPermissions: [],
      enabled: microloansNav.isReady && microloansNav.showInSidebar,
    },
    {
      key: 'shifts',
      component: createNavItem(NavShiftsItem, {
        isCollapsed,
        onClick: () => {
          logEvent(EventName.SHIFTS_MODULE_USE, {});
          onSelectMainItem();
        },
        isActive: isActiveMainItemOverride,
      }),
      requiredPermissions: isManager
        ? ROUTE_PERMISSIONS.SHIFTS_BOSS
        : ROUTE_PERMISSIONS.SHIFTS,
      strictPermissions: true,
    },
    {
      key: 'clock',
      component: createNavItem(NavClockItem, {
        isCollapsed,
        onClick: onSelectMainItem,
        isActive: isActiveMainItemOverride,
      }),
      requiredPermissions: [UserPermissions.VIEW_TIME_TRACKING],
      strictPermissions: true,
      enabled: canAccessClock,
    },
    {
      key: 'time-tracking',
      component: createNavItem(NavTimeTrackingItem, {
        isCollapsed,
        onClick: onSelectMainItem,
        isActive: isActiveMainItemOverride,
      }),
      requiredPermissions: isManager
        ? ROUTE_PERMISSIONS.TIME_TRACKING_BOSS
        : ROUTE_PERMISSIONS.TIME_TRACKING,
      strictPermissions: true,
    },
    {
      key: 'vacations',
      component: (
        <NavTimeOffItem
          isCollapsed={isCollapsed}
          onClick={onSelectMainItem}
          isActive={isActiveMainItemOverride}
        />
      ),
      requiredPermissions: ROUTE_PERMISSIONS.VACATIONS,
    },
    {
      key: 'performance',
      component: (
        <NavPerformanceItem
          isCollapsed={isCollapsed}
          onClick={onSelectMainItem}
          isActive={isActiveMainItemOverride}
        />
      ),
      requiredPermissions: ROUTE_PERMISSIONS.PERFORMANCE,
    },
    {
      key: 'goals',
      component: (
        <NavGoalsItem
          isCollapsed={isCollapsed}
          onClick={onSelectMainItem}
          isActive={isActiveMainItemOverride}
        />
      ),
      requiredPermissions: ROUTE_PERMISSIONS.GOALS,
    },
    {
      key: 'people',
      component: (
        <NavPeopleItem
          isCollapsed={isCollapsed}
          onClick={onSelectMainItem}
          isActive={isActiveMainItemOverride}
        />
      ),
      requiredPermissions: ROUTE_PERMISSIONS.PEOPLE,
    },
    {
      key: 'org-chart',
      component: (
        <NavOrgChartItem
          isCollapsed={isCollapsed}
          onClick={onSelectMainItem}
          isActive={isActiveMainItemOverride}
        />
      ),
      requiredPermissions: ROUTE_PERMISSIONS.ORG_CHART,
    },
    {
      key: 'files',
      component: (
        <NavFilesItem
          isCollapsed={isCollapsed}
          onClick={onSelectMainItem}
          isActive={isActiveMainItemOverride}
        />
      ),
      requiredPermissions: ROUTE_PERMISSIONS.FILES,
    },
    {
      key: 'learnings',
      component: (
        <NavLearningsItem
          isCollapsed={isCollapsed}
          onClick={onSelectMainItem}
          isActive={isActiveMainItemOverride}
        />
      ),
      requiredPermissions: [
        ...ROUTE_PERMISSIONS.COURSES,
        ...ROUTE_PERMISSIONS.PATHS,
        ...ROUTE_PERMISSIONS.SESSIONS,
      ],
    },
    {
      key: 'scorm-courses',
      component: (
        <NavScormItem
          isCollapsed={isCollapsed}
          onClick={onSelectMainItem}
          isActive={isActiveMainItemOverride}
        />
      ),
      requiredPermissions: ROUTE_PERMISSIONS.SCORMS,
    },
    {
      key: 'employee_lifecycle',
      component: (
        <NavEmployeeLifecycleItem
          isCollapsed={isCollapsed}
          onClick={onSelectMainItem}
          isActive={isActiveMainItemOverride}
        />
      ),
      requiredPermissions: ROUTE_PERMISSIONS.EMPLOYEE_LIFECYCLE,
      requiredFlag: 'ENABLE_EMPLOYEE_LIFECYCLE',
    },
    {
      key: 'tasks',
      component: (
        <NavTasksItem
          isCollapsed={isCollapsed}
          onClick={onSelectMainItem}
          isActive={isActiveMainItemOverride}
        />
      ),
      requiredPermissions: ROUTE_PERMISSIONS.EMPLOYEE_LIFECYCLE,
      requiredFlag: 'ENABLE_EMPLOYEE_LIFECYCLE',
    },
    {
      key: 'onboarding',
      component: (
        <NavOnBoardingItem
          isCollapsed={isCollapsed}
          onClick={onSelectMainItem}
          isActive={isActiveMainItemOverride}
        />
      ),
      requiredPermissions: ROUTE_PERMISSIONS.ONBOARDING,
    },
    {
      key: 'people-experience',
      component: (
        <NavPeopleExperienceItem
          isCollapsed={isCollapsed}
          onClick={onSelectMainItem}
          isActive={isActiveMainItemOverride}
        />
      ),
      requiredPermissions: ROUTE_PERMISSIONS.PEOPLE_EXPERIENCE,
    },
    {
      key: 'surveys',
      component: (
        <NavSurveysItem
          isCollapsed={isCollapsed}
          onClick={onSelectMainItem}
          isActive={isActiveMainItemOverride}
        />
      ),
      requiredPermissions: ROUTE_PERMISSIONS.SURVEYS,
    },
    {
      key: 'documents',
      component: (
        <NavDocumentsItem
          isCollapsed={isCollapsed}
          onClick={onSelectMainItem}
          isActive={isActiveMainItemOverride}
        />
      ),
      requiredPermissions: ROUTE_PERMISSIONS.DOCUMENTS,
    },
    {
      key: 'marketplace',
      component: (
        <NavMarketplaceItem
          isCollapsed={isCollapsed}
          onClick={onSelectMainItem}
          isActive={isActiveMainItemOverride}
        />
      ),
      requiredPermissions: ROUTE_PERMISSIONS.MARKETPLACE,
    },
    {
      key: 'shortcut',
      component: (
        <NavShortcutItem
          isCollapsed={isCollapsed}
          onClick={onSelectShortcutIcon}
          isActive={isShortcutActive}
        />
      ),
      requiredPermissions: ROUTE_PERMISSIONS.WIDGETS,
    },
  ];

  const { hasAll: canViewWidgets } = usePermissions([VIEW_WIDGET]);

  const { data } = useQuery(widgetKeys.list(), getWidgetList, {
    enabled: canViewWidgets,
  });

  useEffect(() => {
    setLinks(getActiveUrls(data?.data));
  }, [data?.data]);

  useEffect(() => {
    if (isDownMd && !isActiveSubMenu) {
      collapseMenu();
    }
  }, [location.pathname, isDownMd, isActiveSubMenu]);

  useEffect(() => {
    const groupsIsDownMd = isDownMd && isGroupsActive && !openBackdrop;
    if (groupsIsDownMd) {
      // Make space by minimizing the sidebar
      onSubMenu(false);
    }
  }, [isDownMd, isGroupsActive, openBackdrop]);

  useEffect(() => {
    const sidebarRef = document.getElementById('left-sidebar');
    if (sidebarRef?.style) {
      sidebarRef.style.overflowY = 'hidden';
    }
  }, []);

  if (hidden) return null;

  const handleMouseOver = () => {
    const sidebarRef = document.getElementById('left-sidebar');
    if (sidebarRef?.style) {
      sidebarRef.style.overflowY = 'auto';
    }
  };

  const handleMouseOut = () => {
    const sidebarRef = document.getElementById('left-sidebar');
    if (sidebarRef?.style) {
      sidebarRef.style.overflowY = 'hidden';
    }
  };

  let filteredItems = sidebarItems;

  // 1. Filter sidebar items by permissions
  filteredItems = filteredItems.filter(item =>
    item?.strictPermissions
      ? hasAllPermissions(permissions, item.requiredPermissions)
      : hasAnyPermissions(permissions, item.requiredPermissions),
  );

  // 2. Filter sidebar items by feature flags
  filteredItems = filteredItems.filter(item => {
    if (!item.requiredFlag) return true;
    return checkFeatureFlag(item.requiredFlag);
  });

  // 3. Filter sidebar items by enabled
  filteredItems = filteredItems.filter(item => {
    if (!('enabled' in item)) return true;
    return item.enabled;
  });

  const content = (
    <Box
      id="sidebar"
      sx={{
        display: 'flex',
        flexDirection: 'row',
        minHeight: '100%',
        height: 'fit-content',
        pt: `${NAVBAR_HEIGHT}px`,
        overflowX: 'hidden',
      }}
    >
      <Box
        id="left-sidebar"
        onMouseOver={handleMouseOver}
        onMouseOut={handleMouseOut}
        sx={{
          width: isCollapsed ? SIDEBAR_COLLAPSED_WIDTH : SIDEBAR_WIDTH,
          minWidth: isCollapsed ? SIDEBAR_COLLAPSED_WIDTH : SIDEBAR_WIDTH,
          borderRight: ({ palette }) =>
            `1px solid ${palette.new.border.neutral.default}`,
          overflowX: 'hidden',
        }}
      >
        <Scrollbar options={{ suppressScrollX: true }}>
          <HuGoThemeProvider>
            <HuSidebar
              isCollapsed={isCollapsed}
              pathname={location.pathname}
              customNavSection={<NavSection filteredItems={filteredItems} />}
            />
          </HuGoThemeProvider>
        </Scrollbar>
      </Box>
      {isGroupsActive && isSubMenuOpened && (
        <Suspense
          fallback={
            <Stack
              sx={{
                width: '100%',
                height: '100%',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <HuSpinner />
            </Stack>
          }
        >
          <SidebarGroupsSubMenu onGroupClick={onSelectGroupItem} />
        </Suspense>
      )}
      {isShortcutActive && isSubMenuOpened && (
        <ShortcutsSubmenu
          links={links}
          onSelectShortcutItem={onSelectShortcutItem}
        />
      )}
    </Box>
  );

  if (isCollapsed) {
    return (
      <>
        <Backdrop
          sx={{ zIndex: 100 }}
          open={openBackdrop}
          onClick={onBackdropClick}
        />
        <Drawer
          anchor="left"
          id="sidebar-drawer"
          open={isCollapsed}
          onClose={() => onSubMenu(false)}
          transitionDuration={0}
          PaperProps={{
            sx: {
              backgroundColor: 'background.paper',
              height: '100%  !important',
              width:
                isActiveSubMenu && isSubMenuOpened
                  ? SUB_MENU_WIDTH + SIDEBAR_COLLAPSED_WIDTH
                  : SIDEBAR_COLLAPSED_WIDTH,
              overflow: isActiveSubMenu && isSubMenuOpened ? 'auto' : 'hidden',
            },
          }}
          variant="persistent"
        >
          {content}
        </Drawer>
      </>
    );
  }

  if (isDownMd) {
    return (
      <Drawer
        anchor="left"
        id="sidebar-drawer"
        onClose={onBackdropMdClick}
        open={!isCollapsed}
        PaperProps={{
          sx: {
            backgroundColor: 'background.paper',
            width:
              isActiveSubMenu && isSubMenuOpened
                ? SIDEBAR_WIDTH + SUB_MENU_WIDTH
                : SIDEBAR_WIDTH,
          },
        }}
        variant="temporary"
      >
        {content}
      </Drawer>
    );
  }

  return (
    <>
      <Backdrop
        sx={{ zIndex: 100 }}
        open={openBackdrop}
        onClick={onBackdropClick}
      />
      <Drawer
        anchor="left"
        id="sidebar-drawer"
        open={!isCollapsed}
        onClose={() => onSubMenu(false)}
        transitionDuration={0}
        PaperProps={{
          sx: {
            backgroundColor: 'background.paper',
            overflowX: 'hidden',
            width:
              isActiveSubMenu && isSubMenuOpened
                ? SIDEBAR_WIDTH + SUB_MENU_WIDTH
                : SIDEBAR_WIDTH,
          },
        }}
        variant="persistent"
      >
        {content}
      </Drawer>
    </>
  );
};

export default DashboardSidebar;
