import { Fragment, FunctionComponent, MouseEventHandler, useMemo } from 'react';
import List from '@mui/material/List';
import ListSubheader from '@mui/material/ListSubheader';
import { LinkToPage } from '@/utils';
import { usePathname } from '@/i18n/navigation';
import { matchActivePath } from '../matchActivePath';
import SideBarNavItem from './SideBarNavItem';

interface Props {
  items: Array<LinkToPage>;
  showIcons?: boolean;
  onClick?: MouseEventHandler;
}

/**
 * Renders list of Navigation Items inside SideBar, sectioned into subheaders when consecutive
 * items share a `group` (e.g. the nurse workspace's امروز/حرفهٔ من/مالی/پشتیبانی sections);
 * ungrouped lists (admin/partner/public) render flat exactly as before.
 * @component SideBarNavList
 * @param {array} items - list of objects to render as navigation items
 * @param {boolean} [showIcons] - icons in navigation items are visible when true
 * @param {function} [onClick] - optional callback called when some navigation item was clicked
 */
const SideBarNavList: FunctionComponent<Props> = ({ items, showIcons, onClick }) => {
  const pathname = usePathname();
  const activePath = useMemo(
    () => matchActivePath(pathname, items.map((item) => item.path)),
    [pathname, items]
  );

  return (
    <List component="nav" sx={{ width: '100%' }}>
      {items.map((item, index) => {
        const showHeader = Boolean(item.group) && item.group !== items[index - 1]?.group;
        return (
          <Fragment key={`${item.title}-${item.path}`}>
            {showHeader && <ListSubheader component="div" disableSticky>{item.group}</ListSubheader>}
            <SideBarNavItem
              icon={showIcons ? item.icon : undefined}
              path={item.path}
              title={item.title}
              subtitle={item.subtitle}
              selected={item.path === activePath}
              onClick={onClick}
            />
          </Fragment>
        );
      })}
    </List>
  );
};

export default SideBarNavList;
