'use client';

import React, { useState } from 'react';
import { usePathname } from 'next/navigation';
import Collapse from '@mui/material/Collapse';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import { Theme } from '@mui/material/styles';
import useMediaQuery from '@mui/material/useMediaQuery';
import { styled, useTheme } from '@mui/material/styles';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';
import NavItem from './NavItem';
import { MenuItemType } from '../types/sidebar';

interface NavCollapseProps {
  menu: MenuItemType;
  level: number;
  pathWithoutLastPart: any;
  pathDirect: any;
  hideMenu: boolean | string;
  onClick: (event: React.MouseEvent<HTMLElement>) => void;
}

interface StyledListItemButtonProps {
  open?: boolean;
  active?: boolean;
  level?: number;
  hideMenu?: boolean | string;
}

const StyledListItemButton = styled(ListItemButton, {
  shouldForwardProp: (prop) =>
    prop !== 'open' &&
    prop !== 'active' &&
    prop !== 'level' &&
    prop !== 'hideMenu',
})<StyledListItemButtonProps>(
  ({ theme, open, active, level = 1, hideMenu }) => ({
    marginBottom: '2px',
    padding: '8px 10px',
    paddingLeft: hideMenu ? '10px' : level > 2 ? `${level * 15}px` : '10px',
    backgroundColor: open && level < 2 ? theme.palette.primary.main : '',
    whiteSpace: 'nowrap',
    borderRadius: '7px',
    '&:hover': {
      backgroundColor:
        active || open
          ? theme.palette.primary.main
          : theme.palette.primary.light,
      color: active || open ? 'white' : theme.palette.primary.main,
    },
    color:
      open && level < 2
        ? 'white'
        : level > 1 && open
          ? theme.palette.primary.main
          : theme.palette.text.secondary,
  })
);

const StyledListItemIcon = styled(ListItemIcon)(() => ({
  minWidth: '36px',
  padding: '3px 0',
  color: 'inherit',
}));

export default function NavCollapse({
  menu,
  level,
  pathWithoutLastPart,
  pathDirect,
  hideMenu,
  onClick,
}: NavCollapseProps) {
  const lgDown = useMediaQuery((theme: Theme) => theme.breakpoints.down('lg'));
  const Icon = menu?.icon as React.ComponentType<any>;
  const theme = useTheme();
  const pathname = usePathname();
  const [open, setOpen] = useState(false);
  const menuIcon = Icon ? <Icon /> : null;
  const isActive = pathWithoutLastPart === menu.href;

  const handleClick = () => {
    setOpen(!open);
  };

  // menu collapse for sub-levels
  React.useEffect(() => {
    setOpen(false);
    menu?.children?.forEach((item: any) => {
      if (item?.href === pathname) {
        setOpen(true);
      }
    });
  }, [pathname, menu.children]);

  // If Menu has Children
  const submenus = menu.children?.map((item: any) => {
    if (item.children) {
      return (
        <NavCollapse
          key={item?.id}
          menu={item}
          level={level + 1}
          pathWithoutLastPart={pathWithoutLastPart}
          pathDirect={pathDirect}
          hideMenu={hideMenu}
          onClick={onClick}
        />
      );
    } else {
      return (
        <NavItem
          key={item.id}
          item={item}
          level={level + 1}
          pathDirect={pathDirect}
          hideMenu={hideMenu}
          onClick={lgDown ? onClick : () => {}}
        />
      );
    }
  });

  return (
    <>
      <StyledListItemButton
        onClick={handleClick}
        selected={isActive}
        open={open}
        active={isActive}
        level={level}
        hideMenu={hideMenu}
        key={menu?.id}
      >
        <StyledListItemIcon>{menuIcon}</StyledListItemIcon>
        <ListItemText color="inherit">
          {hideMenu ? '' : <>{menu.title}</>}
        </ListItemText>
        {!open ? (
          <KeyboardArrowDownIcon fontSize="small" />
        ) : (
          <KeyboardArrowUpIcon fontSize="small" />
        )}
      </StyledListItemButton>
      <Collapse in={open} timeout="auto">
        {submenus}
      </Collapse>
    </>
  );
}
