"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
module.exports = CheckoutForm;
var _jsxRuntime = require("react/jsx-runtime");
var _ahooks = require("ahooks");
var _noop = _interopRequireDefault(require("lodash/noop"));
var _react = require("react");
var _ufo = require("ufo");
var _withTracker = require("@arcblock/ux/lib/withTracker");
var _api = _interopRequireDefault(require("../libs/api"));
var _util = require("../libs/util");
var _payment = _interopRequireDefault(require("../payment"));
var _theme = require("../theme");
var _donationForm = _interopRequireDefault(require("../payment/donation-form"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const promises = {};
const startFromPaymentLink = (id, params) => {
  if (!promises[id]) {
    promises[id] = _api.default.post(`/api/checkout-sessions/start/${id}?${(0, _util.mergeExtraParams)(params)}`).then(res => res?.data).finally(() => {
      setTimeout(() => {
        delete promises[id];
      }, 3e3);
    });
  }
  return promises[id];
};
const fetchCheckoutSession = async id => {
  const {
    data
  } = await _api.default.get(`/api/checkout-sessions/retrieve/${id}`);
  return data;
};
function CheckoutForm({
  id,
  mode = "inline",
  onPaid = _noop.default,
  onError = console.error,
  onChange,
  goBack,
  extraParams = {},
  action = "",
  theme = "default",
  formType = "payment",
  ...restProps
}) {
  if (!id.startsWith("plink_") && !id.startsWith("cs_")) {
    throw new Error("Either a checkoutSession or a paymentLink id is required.");
  }
  const type = id.startsWith("plink_") ? "paymentLink" : "checkoutSession";
  const [state, setState] = (0, _ahooks.useSetState)({
    completed: false,
    appError: null
  });
  const {
    error: apiError,
    data
  } = (0, _ahooks.useRequest)(() => type === "paymentLink" ? startFromPaymentLink(id, extraParams) : fetchCheckoutSession(id));
  (0, _react.useEffect)(() => {
    if (type === "paymentLink" && mode === "standalone" && data) {
      window.history.replaceState(null, "", (0, _ufo.joinURL)((0, _util.getPrefix)(), `/checkout/pay/${data.checkoutSession.id}?${(0, _util.mergeExtraParams)(extraParams)}`));
    }
  }, [type, mode, data, extraParams]);
  const handlePaid = result => {
    setState({
      completed: true
    });
    onPaid?.(result);
    const paySuccessEvent = {
      action: "paySuccess",
      // @ts-ignore 后续升级的话就会报错了，移除这个 lint 即可
      mode: data?.checkoutSession?.mode,
      success: true
    };
    _withTracker.ReactGA.event(paySuccessEvent.action, paySuccessEvent);
  };
  const handleError = err => {
    console.error(err);
    setState({
      appError: err
    });
    onError?.(err);
    const payFailedEvent = {
      action: "payFailed",
      // @ts-ignore后续升级的话就会报错了，移除这个 lint 即可
      mode: data?.checkoutSession?.mode,
      errorMessage: err.message,
      success: false
    };
    _withTracker.ReactGA.event(payFailedEvent.action, payFailedEvent);
  };
  const Checkout = formType === "donation" ? /* @__PURE__ */(0, _jsxRuntime.jsx)(_donationForm.default, {
    checkoutSession: data?.checkoutSession,
    paymentMethods: data?.paymentMethods,
    paymentIntent: data?.paymentIntent,
    paymentLink: data?.paymentLink,
    customer: data?.customer,
    completed: state.completed,
    error: apiError,
    onPaid: handlePaid,
    onError: handleError,
    onChange,
    goBack,
    mode,
    action,
    id,
    ...restProps
  }) : /* @__PURE__ */(0, _jsxRuntime.jsx)(_payment.default, {
    checkoutSession: data?.checkoutSession,
    paymentMethods: data?.paymentMethods,
    paymentIntent: data?.paymentIntent,
    paymentLink: data?.paymentLink,
    customer: data?.customer,
    completed: state.completed,
    error: apiError,
    onPaid: handlePaid,
    onError: handleError,
    onChange,
    goBack,
    mode,
    action,
    ...restProps
  });
  if (theme === "inherit") {
    return Checkout;
  }
  if (theme && typeof theme === "object") {
    return /* @__PURE__ */(0, _jsxRuntime.jsx)(_theme.PaymentThemeProvider, {
      theme,
      children: Checkout
    });
  }
  return /* @__PURE__ */(0, _jsxRuntime.jsx)(_theme.PaymentThemeProvider, {
    children: Checkout
  });
}