import React from "react";

import Button, { ButtonProps } from "@mui/material/Button";

import { useSnackbar } from "notistack";
import { OpenAPI } from "openapi-types";

import { useApi } from "../contexts/ApiContext";
import { PageProps } from "../types";

export interface ActionButtonProps extends ButtonProps {
  operation: string;
  request?: OpenAPI.Request;
  init?: RequestInit;
  successMessage: string;
  errorMessage: string;
  refresh: PageProps["refresh"];
}

export const ActionButton: React.FC<ActionButtonProps> = ({
  operation,
  successMessage,
  errorMessage,
  children,
  variant = "outlined",
  refresh,
  onClick,
  request,
  init,
  ...props
}) => {
  const api = useApi();
  const { enqueueSnackbar } = useSnackbar();

  const handleClick = async () => {
    const action = api.operations[operation];
    if (!action) {
      throw new Error(`Invalid action "${operation}".`);
    }

    const response = await action.call(request, init);

    if (response.ok) {
      enqueueSnackbar(successMessage, { variant: "success" });
      refresh();
      return successMessage;
    } else {
      console.error("[ACTION_BUTTON]", response);
      enqueueSnackbar(errorMessage, {
        variant: "error",
      });
      throw new Error(errorMessage);
    }
  };

  return (
    <Button size="medium" variant={variant} onClick={onClick ?? handleClick} {...props}>
      {children}
    </Button>
  );
};

export default ActionButton;
