import { NavGroup } from './NavGroup';
import { NavList } from './NavList';
import { useMenu } from '@/components/Layout/MenuProvider';
import { useLayoutMediaState } from '@/components/Layout/Provider';
import { useThemeConfig } from '@/components/Layout/ThemeProvider';
import { SxProps, Typography } from '@mui/material';
import _ from 'lodash';
import { useState } from 'react';

type INavigationProps = {
  sx?: SxProps;
};

type IItem = { title: any; elements: any; icon: any };

function Navigation(props: INavigationProps) {
  const { horizontal } = useLayoutMediaState();
  const { menu, isLoading } = useMenu();
  const [selectedItems, setSelectedItems] = useState<string>('');
  const [selectedLevel, setSelectedLevel] = useState<number>(0);
  const { horizontalMaxItems } = useThemeConfig();
  const lastItem = horizontal ? horizontalMaxItems : undefined;

  let lastItemIndex = isLoading ? 0 : (menu ?? []).length - 1;
  let remItems: Array<IItem> = [];
  let lastItemId: string;

  if (!isLoading && lastItem && lastItem < (menu ?? []).length) {
    lastItemId = (menu ?? [])[lastItem - 1].id;
    lastItemIndex = lastItem - 1;
    remItems = (menu ?? []).slice(lastItem - 1, (menu ?? []).length).map((item) => ({
      title: item.title,
      elements: item.children,
      icon: item.icon
    }));
  }
  return (
    <NavList {...props}>
      {!isLoading &&
        _.map((menu ?? []).slice(0, lastItemIndex + 1), (item) => {
          const { type } = item;

          switch (type) {
            case 'group':
              return (
                <NavGroup
                  key={item.id}
                  item={item}
                  setSelectedItems={setSelectedItems}
                  setSelectedLevel={setSelectedLevel}
                  selectedLevel={selectedLevel}
                  selectedItems={selectedItems}
                  lastItem={lastItem}
                  remItems={remItems}
                  lastItemId={lastItemId}
                />
              );
            default:
              return (
                <Typography key={item.id} variant="h6" color="error" align="center">
                  Fix - Navigation Group
                </Typography>
              );
          }
        })}
    </NavList>
  );
}

export { Navigation };
