"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DonateContext = exports.DonateConsumer = void 0;
exports.DonateProvider = DonateProvider;
exports.clearDonateSettings = exports.clearDonateCache = void 0;
exports.useDonateContext = useDonateContext;
var _jsxRuntime = require("react/jsx-runtime");
var _ahooks = require("ahooks");
var _react = require("react");
var _Toast = _interopRequireDefault(require("@arcblock/ux/lib/Toast"));
var _context = require("@arcblock/ux/lib/Locale/context");
var _material = require("@mui/material");
var _api = _interopRequireDefault(require("../libs/api"));
var _util = require("../libs/util");
var _cachedRequest = require("../libs/cached-request");
var _confirm = _interopRequireDefault(require("../components/confirm"));
var _payment = require("./payment");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const DonateContext = exports.DonateContext = (0, _react.createContext)({
  api: _api.default
});
const {
  Provider,
  Consumer
} = DonateContext;
exports.DonateConsumer = Consumer;
const fetchDonateSetting = (params, forceRefresh = false) => {
  const livemode = localStorage.getItem("livemode") !== "false";
  const cacheKey = `donate-settings-${params.mountLocation}-${livemode}`;
  const cachedRequest = new _cachedRequest.CachedRequest(cacheKey, () => _api.default.post("/api/settings", {
    ...params,
    type: "donate",
    livemode,
    settings: params.defaultSettings
  }), {
    ttl: 1e3 * 60 * 60,
    strategy: "local"
  });
  return cachedRequest.fetch(forceRefresh);
};
function DonateProvider({
  mountLocation,
  description,
  defaultSettings = {},
  children,
  active = true,
  enableDonate = false
}) {
  const {
    t
  } = (0, _context.useLocaleContext)();
  const [showConfirm, setShowConfirm] = (0, _react.useState)(false);
  const {
    session
  } = (0, _payment.usePaymentContext)();
  const isAdmin = ["owner", "admin"].includes(session?.user?.role);
  const {
    data = {
      settings: {},
      active: true
    },
    error,
    run,
    loading
  } = (0, _ahooks.useRequest)(forceRender => fetchDonateSetting({
    mountLocation,
    description,
    defaultSettings,
    active,
    componentDid: window.blocklet?.componentId?.split("/").pop()
  }, forceRender), {
    refreshDeps: [mountLocation],
    onError: err => {
      _Toast.default.error((0, _util.formatError)(err));
    }
  });
  const updateSettings = async newSettings => {
    try {
      const livemode = localStorage.getItem("livemode") !== "false";
      await _api.default.put(`/api/settings/${mountLocation}`, {
        livemode,
        settings: newSettings
      });
      run(true);
      _Toast.default.success(t("common.saved"));
    } catch (err) {
      _Toast.default.error((0, _util.formatError)(err));
      throw err;
    }
  };
  const supportPaymentKit = (0, _util.getPaymentKitComponent)();
  const handleEnable = async () => {
    if (!enableDonate || !data || data?.active) return;
    try {
      await _api.default.put(`/api/settings/${data.id}`, {
        active: true
      });
      if (supportPaymentKit) {
        setShowConfirm(true);
      } else {
        _Toast.default.success(t("payment.checkout.donation.enableSuccess"));
        run(true);
      }
    } catch (err) {
      _Toast.default.error((0, _util.formatError)(err));
    }
  };
  if (loading || error) {
    return null;
  }
  return /* @__PURE__ */(0, _jsxRuntime.jsx)(Provider, {
    value: {
      settings: data,
      refresh: run,
      updateSettings,
      api: _api.default
    },
    children: data?.active === false ? /* @__PURE__ */(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
      children: [enableDonate && isAdmin && /* @__PURE__ */(0, _jsxRuntime.jsxs)(_material.Stack, {
        spacing: 1,
        sx: {
          alignItems: "center"
        },
        children: [/* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Typography, {
          sx: {
            color: "text.secondary"
          },
          children: t("payment.checkout.donation.inactive")
        }), /* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Button, {
          size: "small",
          variant: "outlined",
          color: "primary",
          onClick: handleEnable,
          sx: {
            width: "fit-content"
          },
          children: t("payment.checkout.donation.enable")
        })]
      }), showConfirm && /* @__PURE__ */(0, _jsxRuntime.jsx)(_confirm.default, {
        title: t("payment.checkout.donation.enableSuccess"),
        message: t("payment.checkout.donation.configPrompt"),
        cancel: t("payment.checkout.donation.later"),
        confirm: t("payment.checkout.donation.configNow"),
        onCancel: () => {
          setShowConfirm(false);
          run(true);
        },
        color: "primary",
        onConfirm: () => {
          run(true);
          (0, _util.openDonationSettings)(false);
          setShowConfirm(false);
        }
      })]
    }) : children
  });
}
function useDonateContext() {
  const context = (0, _react.useContext)(DonateContext);
  return context;
}
const clearDonateCache = mountLocation => {
  const livemode = localStorage.getItem("livemode") !== "false";
  const cacheKey = `donate-settings-${mountLocation}-${livemode}`;
  localStorage.removeItem(cacheKey);
};
exports.clearDonateCache = clearDonateCache;
const clearDonateSettings = async mountLocation => {
  try {
    const livemode = localStorage.getItem("livemode") !== "false";
    await _api.default.delete(`/api/settings/${mountLocation}`, {
      params: {
        livemode
      }
    });
    clearDonateCache(mountLocation);
  } catch (err) {
    _Toast.default.error((0, _util.formatError)(err));
  }
};
exports.clearDonateSettings = clearDonateSettings;