import { memo, useMemo } from 'react';
import { useStore } from 'stores/StoreProvider';
import { observer } from 'mobx-react-lite';
import { leftSidebarMenuItem } from './helpers';
import { LeftOutlined, RightOutlined } from '@ant-design/icons';
import { Layout, Menu } from 'antd';
import { TypeLeftSidebar } from 'components/Dashboard/types';

import styles from './LeftSidebar.module.scss';

const { Sider: SideBar } = Layout;

const LeftSidebar = observer(
  ({
    leftSideBarContent,
  }: {
    leftSideBarContent: TypeLeftSidebar[];
  }): JSX.Element => {
    const { isCollapsed, toggleCollapsed } = useStore().helpersStore;

    const Direction = isCollapsed ? RightOutlined : LeftOutlined;

    const onCollapse = (): void => {
      toggleCollapsed(!isCollapsed);
    };

    const pathname = window.location.pathname;

    const defaultKey = useMemo((): number => {
      let selectedItem = 0;
      leftSideBarContent.forEach((item, index) => {
        const { subMenu } = leftSideBarContent[index];
        if (subMenu) {
          subMenu.forEach((_, i) => {
            if (subMenu[i].path === pathname) selectedItem = subMenu[i].key;
          });
        } else {
          if (leftSideBarContent[index].path === pathname)
            selectedItem = leftSideBarContent[index].key;
        }
      });

      return selectedItem;
    }, [leftSideBarContent, pathname]);

    return (
      <SideBar
        theme="light"
        className={styles['sidebar']}
        trigger={null}
        collapsible
        collapsed={isCollapsed}
      >
        <Menu
          mode="inline"
          defaultSelectedKeys={[`${defaultKey}`]}
          defaultOpenKeys={['2']}
          items={leftSidebarMenuItem(leftSideBarContent, isCollapsed)}
          className={styles['customMenu']}
        />
        <div className={styles['sidebar-direction']}>
          <Direction
            className={styles['sidebar-direction_icon']}
            onClick={onCollapse}
          />
        </div>
      </SideBar>
    );
  },
);

export default memo(LeftSidebar);
