import React from "react";
import PropTypes from "prop-types";
import { IconButton, Tooltip } from "@mui/material";

const ActionButton = React.forwardRef((props, ref) => {
  const { action, machine, callback, disabled } = props;
  const id = `machine-item-${machine.machineId}-${action.code}`;
  const handleActionClick = event => {
    action.effect(machine, event);
    callback && callback(machine);
    event.stopPropagation();
  };

  return (
    <Tooltip id={`machine-item-${machine.machineId}-${action.code}-tooltip`} title={action.tooltip}>
      <span>
        <IconButton
          id={id}
          size={"small"}
          sx={{ padding: "0.2rem" }}
          onFocus={event => event.stopPropagation()}
          onClick={handleActionClick}
          disabled={disabled}
          ref={ref}
        >
          <action.icon />
        </IconButton>
      </span>
    </Tooltip>
  );
});

ActionButton.propTypes = {
  machine: PropTypes.shape({
    machineId: PropTypes.number.isRequired
  }).isRequired,
  action: PropTypes.shape({
    code: PropTypes.string.isRequired,
    tooltip: PropTypes.string.isRequired,
    effect: PropTypes.func.isRequired,
    icon: PropTypes.elementType.isRequired
  }).isRequired,
  callback: PropTypes.func,
  disabled: PropTypes.bool
};

ActionButton.displayName = "ActionButton";

export default ActionButton;
