import { type FC } from 'react';
import { matchPath } from 'react-router-dom';

import { List } from '@mui/material';

import { type Item, type NavSectionProps } from '../../types';
import NavItem from '../NavItem';

const renderNavItems = ({
  depth = 0,
  items,
  pathname,
  isCollapsed,
  openMenu,
}: {
  items: Item[];
  pathname: string;
  depth?: number;
  isCollapsed?: boolean;
  openMenu?: () => void;
}) => (
  <List
    disablePadding
    sx={{
      '& > *:not(:last-child)': {
        mb: depth > 0 ? 0 : 1.5,
      },
    }}
  >
    {items.map((item, index) => {
      const key = `${item.key}-${depth}`;
      const match = !!matchPath(
        depth === 0 ? `${item.path}/*` : item.path,
        pathname,
      );
      const hasChildren = item.subItems && !isCollapsed;
      const hasChildrenButIsCollapsed = item.subItems && isCollapsed;

      return (
        <NavItem
          active={match}
          depth={depth}
          icon={item.icon}
          info={item.info}
          key={
            hasChildren
              ? `${key}-${isCollapsed ? 'collapsed' : 'expanded'}`
              : key
          }
          open={match}
          path={item.path}
          title={item.title}
          isCollapsed={isCollapsed}
          isLastChild={index === items.length - 1}
          openMenu={openMenu}
          skipLinkBehavior={item.skipLinkBehavior}
          onClick={item.onClick}
          fallbackPath={item.subItems?.[0]?.path}
          {...(item.subItems && {
            hasChildrenButCollapsed: hasChildrenButIsCollapsed,
            children:
              hasChildren &&
              renderNavItems({
                depth: depth + 1,
                items: item.subItems,
                pathname,
                isCollapsed,
                openMenu,
              }),
          })}
        />
      );
    })}
  </List>
);

const NavSection: FC<NavSectionProps> = props => {
  const { items, pathname, isCollapsed, openMenu } = props;

  return (
    <List
      sx={{
        '& + &': {
          mt: 3,
        },
      }}
      disablePadding
    >
      {renderNavItems({
        items,
        pathname: pathname!,
        isCollapsed,
        openMenu,
      })}
    </List>
  );
};

export type { NavSectionProps };

export default NavSection;
