import React from "react";
import {
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Tooltip,
} from "@mui/material";
import { useLocation, useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { DRAWER } from "../../../lib/redux/slices/appSlice";

export const MenuItem = React.memo(
  ({
    icon,
    text,
    route,
    tooltip,
    open,
    disabled = false,
    onClick,
    onClose,
  }) => {
    const navigate = useNavigate();
    const { pathname } = useLocation();
    const dispatch = useDispatch();
    const isSelected = pathname.includes(route);

    const handleClick = () => {
      if (disabled) return;

      dispatch(DRAWER({ right: false, bottom: false, content: null }));

      if (onClick) {
        onClick();
      } else if (route) {
        navigate(route);
      }

      if (onClose) {
        onClose();
      }
    };

    const content = (
      <ListItemButton
        onClick={handleClick}
        selected={isSelected}
        disabled={disabled}
      >
        <ListItemIcon>{icon || null}</ListItemIcon>
        <ListItemText primary={text} />
      </ListItemButton>
    );

    if (tooltip && !open) {
      return (
        <Tooltip title={tooltip} placement="left-start">
          {content}
        </Tooltip>
      );
    }

    return content;
  }
);

MenuItem.displayName = "MenuItem";
