import { IconButton, Tooltip } from "@mui/material";
import { useAlert } from "../hooks/providers/AlertDialogProvider";
import { useConfirm } from "../hooks/providers/ConfirmDialogProvider";

export function StateActionButton<S>(p: {
  currState: S;
  cond: S[];
  icon: React.ReactElement;
  tooltip: string;
  confirmMessage?: string;
  performAction: () => Promise<void>;
  onExecuted: () => void;
}): React.ReactElement {
  const confirm = useConfirm();
  const alert = useAlert();

  if (!p.cond.includes(p.currState)) return <></>;

  const performAction = async () => {
    try {
      if (p.confirmMessage && !(await confirm(p.confirmMessage))) return;
      await p.performAction();
      p.onExecuted();
    } catch (e) {
      console.error(e);
      alert("Failed to perform action! " + e);
    }
  };

  return (
    <Tooltip title={p.tooltip}>
      <IconButton
        size="small"
        onClick={performAction}
        style={{ paddingBottom: "0px", paddingTop: "0px" }}
      >
        {p.icon}
      </IconButton>
    </Tooltip>
  );
}
