/* eslint-disable @typescript-eslint/no-explicit-any */
import { Button, Menu, MenuItem } from "@mui/material";
import { FC, MouseEvent, useState } from "react";
import { useTranslation } from "react-i18next";

export interface NodeMenuProps {
	items: NodeMenuItem[];
}

export interface NodeMenuItem {
	parameter?: any;
	titleTranslationKey: string;
	onClick: (parameter?: any) => void;
}

export const NodeMenuView: FC<NodeMenuProps> = ({ items }) => {
	const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
	const { t } = useTranslation();
	const open = Boolean(anchorEl);

	const handleOpen = (event: MouseEvent<HTMLButtonElement>) => {
		setAnchorEl(event.currentTarget);
		event.stopPropagation();
	};

	const handleClose = (event: MouseEvent<HTMLElement>) => {
		setAnchorEl(null);
		event.stopPropagation();
	};

	const handleClick = (
		event: MouseEvent<HTMLElement>,
		item: NodeMenuItem
	) => {
		handleClose(event);

		item.onClick(item.parameter);
	};

	return (
		<>
			<Button
				size="small"
				id="menu-button"
				aria-controls={open ? "menu" : undefined}
				aria-haspopup="true"
				aria-expanded={open ? "true" : undefined}
				onClick={handleOpen}
			>
				{t("menu")}
			</Button>
			<Menu
				id="menu"
				anchorEl={anchorEl}
				open={open}
				onClose={handleClose}
				MenuListProps={{
					"aria-labelledby": "menu-button",
				}}
			>
				{items.map((item, index) => (
					<MenuItem
						key={index}
						onClick={(e) => handleClick(e, item)}
					>
						{t(item.titleTranslationKey)}
					</MenuItem>
				))}
			</Menu>
		</>
	);
};
