import React from "react";

import { useSnackbar } from "notistack";

import ActionButton, { ActionButtonProps } from "../../../components/ActionButton";
import { useApi } from "../../../contexts/ApiContext";
import { useCardContext } from "../../../contexts/CardContext";
import { useI18n } from "../../../contexts/I18nContext";

export interface CancelSubscriptionButtonProps
  extends Pick<ActionButtonProps, "refresh" | "variant" | "children"> {
  subscriptionId: number;
  handleClose: () => void;
  operation?: string;
}

const CancelSubscriptionButton: React.FC<CancelSubscriptionButtonProps> = ({
  subscriptionId,
  refresh,
  variant = "outlined",
  children,
  handleClose,
  operation = "subscription.subscription:cancel",
}) => {
  const { setIsEditing } = useCardContext();
  const { t } = useI18n();

  const successMessage = t("Subscription cancelled successfully.");
  const errorMessage = t("Failed to cancel subscription.");
  const api = useApi();
  const { enqueueSnackbar } = useSnackbar();

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

    const response = await action.call({
      params: { subscription_id: subscriptionId },
    });

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

  const handleClick = async () => {
    handleClose();
    action(subscriptionId);
    setIsEditing(false);
  };

  return (
    <>
      <ActionButton
        errorMessage={errorMessage}
        operation="subscription.subscription:cancel"
        refresh={refresh}
        request={{ params: { subscription_id: subscriptionId } }}
        successMessage={successMessage}
        variant={variant}
        onClick={handleClick}
      >
        {children ?? t("Cancel subscription")}
      </ActionButton>
    </>
  );
};

export default CancelSubscriptionButton;
