import { useState } from 'react';
import { Box, Button, Menu, MenuItem } from '@mui/material';
import { useLocation, Link } from 'react-router-dom';

const makePath = (string) =>{
  return "/" + string.toLowerCase().trim().replace(/[\s]+/g, "-").replace(/[^\w-]+/g, "");
}

const NavButton = ({ label, menuItems = [], path = makePath(label) }) => {
  const [anchorEl, setAnchorEl] = useState(null);
  const hasMenu = menuItems.length > 0;
  const location = useLocation();

  const handleMenuOpen = (event) => {
    if (hasMenu) {
      setAnchorEl(event.currentTarget);
    }
  };

  const handleMenuClose = () => {
    setAnchorEl(null);
  };

  const isActive = (path) => location.pathname.startsWith(path);

  return (
    <Box className="nav-button">
      <Button
        onClick={handleMenuOpen}
        variant='nav'
        component={hasMenu ? 'button' : Link}
        to={path}
        sx={(theme) =>({
          borderBottom: isActive(path)
          ? `2px solid ${theme.palette.primary.main}` : "",
        })}
      >
        {label}
      </Button>
      {hasMenu && (
        <Menu anchorEl={anchorEl} open={Boolean(anchorEl)} onClose={handleMenuClose}>
          {menuItems.map((item, index) => (
            <MenuItem
              key={index}
              component={Link}
              to={path + makePath(item)}
              onClick={handleMenuClose}
            >
              {item}
            </MenuItem>
          ))}
        </Menu>
      )}
    </Box>
  );
};

export default NavButton;
