"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
module.exports = CheckoutTable;
var _jsxRuntime = require("react/jsx-runtime");
var _context = require("@arcblock/ux/lib/Locale/context");
var _Toast = _interopRequireDefault(require("@arcblock/ux/lib/Toast"));
var _material = require("@mui/material");
var _system = require("@mui/system");
var _ahooks = require("ahooks");
var _react = require("react");
var _livemode = _interopRequireDefault(require("../components/livemode"));
var _pricingTable = _interopRequireDefault(require("../components/pricing-table"));
var _api = _interopRequireDefault(require("../libs/api"));
var _util = require("../libs/util");
var _form = _interopRequireDefault(require("./form"));
var _theme = require("../theme");
var _truncatedText = _interopRequireDefault(require("../components/truncated-text"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const fetchData = async id => {
  const {
    data
  } = await _api.default.get(`/api/pricing-tables/${id}`);
  return data;
};
const ensureProtocol = url => {
  if (!/^https?:\/\//i.test(url)) {
    return `https://${url}`;
  }
  return url;
};
function CheckoutTableInner({
  id,
  mode,
  onPaid,
  onError,
  onChange,
  extraParams,
  goBack,
  theme
}) {
  if (!id.startsWith("prctbl_")) {
    throw new Error("A valid pricing table id is required.");
  }
  const [sessionId, setSessionId] = (0, _react.useState)("");
  const hashSessionId = window.location.hash.slice(1);
  const {
    t
  } = (0, _context.useLocaleContext)();
  const {
    error,
    loading,
    data
  } = (0, _ahooks.useRequest)(() => fetchData(id));
  if (error) {
    return /* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Alert, {
      severity: "error",
      children: error.message
    });
  }
  if (loading || !data) {
    return /* @__PURE__ */(0, _jsxRuntime.jsx)(_material.CircularProgress, {});
  }
  if (data.items.length === 0) {
    return /* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Alert, {
      severity: "warning",
      children: t("payment.checkout.noPricing")
    });
  }
  const handleSelect = (priceId, currencyId) => {
    _api.default.post(`/api/pricing-tables/${data.id}/checkout/${priceId}?${(0, _util.mergeExtraParams)({
      ...extraParams,
      currencyId
    })}`).then(res => {
      if (mode === "standalone") {
        let {
          url
        } = res.data;
        url = url.indexOf("?") > -1 ? `${url}&currencyId=${currencyId}` : `${url}?currencyId=${currencyId}`;
        window.location.replace(ensureProtocol(url));
      } else {
        window.location.hash = res.data.id;
        setSessionId(res.data.id);
      }
    }).catch(err => {
      console.error(err);
      _Toast.default.error(err.message);
    });
  };
  const prop = {};
  if (goBack) {
    prop.goBack = () => {
      window.location.hash = "";
      if (typeof goBack !== "undefined") {
        goBack();
      }
      setSessionId("");
    };
  }
  if (!sessionId && !hashSessionId) {
    if (mode === "standalone") {
      return /* @__PURE__ */(0, _jsxRuntime.jsxs)(_material.Stack, {
        direction: "column",
        sx: {
          alignItems: "center",
          overflow: {
            xs: "auto",
            md: "hidden"
          },
          height: "100%",
          pt: {
            xs: 2.5,
            md: 7.5
          },
          px: 2.5
        },
        children: [/* @__PURE__ */(0, _jsxRuntime.jsxs)(_system.Box, {
          sx: {
            display: "flex",
            flexDirection: "column",
            fontSize: "24px",
            alignItems: "center",
            margin: {
              xs: "20px 0",
              md: "20px 20px"
            },
            maxWidth: {
              xs: "100%",
              md: 400
            },
            textAlign: "center"
          },
          children: [!data.livemode && /* @__PURE__ */(0, _jsxRuntime.jsx)(_livemode.default, {
            sx: {
              display: "flex",
              marginBottom: "8px",
              width: "fit-content",
              ml: 0
            }
          }), /* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Typography, {
            sx: {
              color: "text.primary",
              fontWeight: 600,
              lineHeight: "32px",
              fontSize: "24px"
            },
            children: /* @__PURE__ */(0, _jsxRuntime.jsx)(_truncatedText.default, {
              text: data.name,
              maxLength: 60,
              useWidth: true
            })
          })]
        }), /* @__PURE__ */(0, _jsxRuntime.jsx)(_pricingTable.default, {
          table: data,
          onSelect: handleSelect
        })]
      });
    }
    return /* @__PURE__ */(0, _jsxRuntime.jsx)(_pricingTable.default, {
      mode: "select",
      table: data,
      onSelect: handleSelect
    });
  }
  return /* @__PURE__ */(0, _jsxRuntime.jsx)(_system.Box, {
    sx: {
      height: "100%"
    },
    children: /* @__PURE__ */(0, _jsxRuntime.jsx)(_form.default, {
      id: hashSessionId || sessionId,
      mode,
      onPaid,
      onError,
      onChange,
      theme,
      ...prop
    })
  });
}
function CheckoutTable(props) {
  if (props.theme === "inherit") {
    return /* @__PURE__ */(0, _jsxRuntime.jsx)(CheckoutTableInner, {
      ...props
    });
  }
  if (props.theme && typeof props.theme === "object") {
    return /* @__PURE__ */(0, _jsxRuntime.jsx)(_theme.PaymentThemeProvider, {
      theme: props.theme,
      children: /* @__PURE__ */(0, _jsxRuntime.jsx)(CheckoutTableInner, {
        ...props
      })
    });
  }
  return /* @__PURE__ */(0, _jsxRuntime.jsx)(_theme.PaymentThemeProvider, {
    children: /* @__PURE__ */(0, _jsxRuntime.jsx)(CheckoutTableInner, {
      ...props
    })
  });
}