import React, { useCallback } from "react";

import { enqueueSnackbar } from "notistack";

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

export interface ResumeSubscriptionButtonProps extends Pick<ActionButtonProps, "refresh"> {
  subscriptionId: number;
}

const ResumeSubscriptionButton: React.FC<ResumeSubscriptionButtonProps> = ({
  subscriptionId,
  refresh,
}) => {
  const { t } = useI18n();
  const api = useApi();
  const openDialog = useDialog();
  const handleClick = useCallback(async () => {
    if (
      await openDialog(
        t("Resume subscription"),
        t("Are you sure you want to resume the subscription?"),
      )
    ) {
      const response = await api.operations["subscription.subscription:resume"].call({
        params: { subscription_id: subscriptionId },
      });

      if (response.ok) {
        enqueueSnackbar(t("Sucessfully resumed subscription"), {
          variant: "success",
        });
      } else {
        enqueueSnackbar(t("Failed to resume subscription"), {
          variant: "error",
        });
        throw response;
      }
      refresh();
    }
  }, [subscriptionId]);
  return (
    <ActionButton
      errorMessage={t("Failed to resume subscription.")}
      operation="subscription.subscription:resume"
      refresh={refresh}
      request={{ params: { subscription_id: subscriptionId } }}
      successMessage={t("Subscription resumed successfully.")}
      onClick={handleClick}
    >
      {t("Resume subscription")}
    </ActionButton>
  );
};

export default ResumeSubscriptionButton;
