import * as React from "react";
import { Menu, MenuItem, ListItemIcon, ListItemText } from "@material-ui/core";

import Card from "@material-ui/core/Card";
import CardHeader from "@material-ui/core/CardHeader";
import CardContent from "@material-ui/core/CardContent";
import IconButton from "@material-ui/core/IconButton";
import MoreVertIcon from "@material-ui/icons/MoreVert";
import { WidgetContainerProps } from "./types";

/**
 * A container for showing custom dashboard widget components
 */
const WidgetContainer: React.FC<WidgetContainerProps> = ({
  children,
  title,
  actions,
  actionComponent,
}) => {
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);

  const handleClick = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

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

  const ActionComponent =
    actionComponent ||
    (actions && (
      <>
        <IconButton title="Menu" onClick={handleClick} aria-label="settings">
          <MoreVertIcon />
        </IconButton>

        <Menu
          id="widget-menu"
          anchorEl={anchorEl}
          keepMounted
          open={Boolean(anchorEl)}
          onClose={handleClose}
        >
          {actions.map((itm, key) => {
            const { icon, label } = itm;
            return (
              <MenuItem
                key={key}
                data-testid="Dashboard-WidgetContainer-MenuItem"
                onClick={() => {
                  itm.onSelect();
                  handleClose();
                }}
              >
                {icon && <ListItemIcon>{icon}</ListItemIcon>}
                <ListItemText primary={label} />
              </MenuItem>
            );
          })}
        </Menu>
      </>
    )) ||
    null;

  return (
    <Card data-testid="Dashboard-WidgetContainer">
      {(title || actions) && (
        <CardHeader title={title} action={ActionComponent} />
      )}
      <CardContent>{children}</CardContent>
    </Card>
  );
};

export default WidgetContainer;
