import { useMemo, useState } from 'react';
import { Box, Collapse, ListItemButton, ListItemText } from '@mui/material';
import { Menu, MenuItemLink } from 'react-admin';
import { useLocation } from 'react-router-dom';
import {
  EQUIPMENT_SIDEBAR_ARCHIVE_FILTER,
  EQUIPMENT_SIDEBAR_IN_WORK_FILTER,
  STATUS_CHANGES_CLOSING_FILTER,
  STATUS_CHANGES_DOWNTIME_FILTER,
  equipmentListSearch,
  statusChangesListSearch,
} from './toirMenuLinks';
import './ToirMenu.css';

export function ToirMenu() {
  const location = useLocation();
  const isStatusChangesRoute = location.pathname.startsWith('/status-changes');
  const [statusChangesOpen, setStatusChangesOpen] = useState(false);

  const statusChangesLinks = useMemo(
    () => ({
      downtime: `/status-changes?${statusChangesListSearch(STATUS_CHANGES_DOWNTIME_FILTER)}`,
      closing: `/status-changes?${statusChangesListSearch(STATUS_CHANGES_CLOSING_FILTER)}`,
    }),
    [],
  );

  return (
    <Menu>
      <MenuItemLink
        className="toir-menu-item"
        to={`/equipment?${equipmentListSearch(EQUIPMENT_SIDEBAR_IN_WORK_FILTER)}`}
        primaryText="В работе"
      />
      <MenuItemLink
        className="toir-menu-item"
        to={`/equipment?${equipmentListSearch(EQUIPMENT_SIDEBAR_ARCHIVE_FILTER)}`}
        primaryText="Архив"
      />
      <ListItemButton
        className="toir-menu-group"
        selected={isStatusChangesRoute}
        onClick={() => setStatusChangesOpen((open) => !open)}
      >
        <ListItemText primary="Журнал актов" />
        <span className={`toir-menu-group__chevron${statusChangesOpen ? ' is-open' : ''}`} aria-hidden>
          <span />
        </span>
      </ListItemButton>
      <Collapse in={statusChangesOpen} timeout="auto" unmountOnExit>
        <Box className="toir-menu-subtree">
          <MenuItemLink
            className="toir-menu-subitem"
            to={statusChangesLinks.downtime}
            primaryText="Простои"
          />
          <MenuItemLink
            className="toir-menu-subitem"
            to={statusChangesLinks.closing}
            primaryText="Закрывающие документы"
          />
        </Box>
      </Collapse>
    </Menu>
  );
}
