'use client';

import Menuitems from '../sidebar/MenuItems';
import { usePathname } from 'next/navigation';
import Box from '@mui/material/Box';
import List from '@mui/material/List';
import useMediaQuery from '@mui/material/useMediaQuery';
import { styled } from '@mui/material/styles';
import NavItem from './components/NavItem';
import NavCollapse from './components/NavCollapse';
import NavGroup from './components/NavGroup';

interface SidebarItemsProps {
  open: boolean;
  onItemClick?: () => void;
}

const StyledSidebarContainer = styled(Box)(() => ({
  paddingLeft: 24,
  paddingRight: 24,
}));

const StyledList = styled(List)(() => ({
  paddingTop: 0,
}));

const SidebarItems = ({ open, onItemClick }: SidebarItemsProps) => {
  const pathname = usePathname();
  const pathDirect = pathname;
  const pathWithoutLastPart = pathname.slice(0, pathname.lastIndexOf('/'));
  const lgUp = useMediaQuery((theme: any) => theme.breakpoints.up('lg'));
  const hideMenu: boolean | string = lgUp ? !open : false;

  const handleItemClick = () => {
    if (onItemClick) {
      onItemClick();
    }
  };

  return (
    <StyledSidebarContainer>
      <StyledList className="sidebarNav">
        {Menuitems.map((item) => {
          // SubHeader
          if (item.subheader) {
            return (
              <NavGroup item={item} hideMenu={hideMenu} key={item.subheader} />
            );

            // If Sub Menu
          } else if (item.children) {
            return (
              <NavCollapse
                menu={item}
                pathDirect={pathDirect}
                hideMenu={hideMenu}
                pathWithoutLastPart={pathWithoutLastPart}
                level={1}
                key={item.id}
                onClick={handleItemClick}
              />
            );

            // If Sub No Menu
          } else {
            return (
              <NavItem
                item={item}
                key={item.id}
                pathDirect={pathDirect}
                hideMenu={hideMenu}
                onClick={handleItemClick}
              />
            );
          }
        })}
      </StyledList>
    </StyledSidebarContainer>
  );
};

export default SidebarItems;
