import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useRequest } from "ahooks";
import { createContext, useContext, useState } from "react";
import Toast from "@arcblock/ux/lib/Toast";
import { useLocaleContext } from "@arcblock/ux/lib/Locale/context";
import { Button, Stack, Typography } from "@mui/material";
import api from "../libs/api.js";
import { formatError, getPaymentKitComponent, openDonationSettings } from "../libs/util.js";
import { CachedRequest } from "../libs/cached-request.js";
import ConfirmDialog from "../components/confirm.js";
import { usePaymentContext } from "./payment.js";
const DonateContext = createContext({ api });
const { Provider, Consumer } = DonateContext;
const fetchDonateSetting = (params, forceRefresh = false) => {
  const livemode = localStorage.getItem("livemode") !== "false";
  const cacheKey = `donate-settings-${params.mountLocation}-${livemode}`;
  const cachedRequest = new CachedRequest(
    cacheKey,
    () => api.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 } = useLocaleContext();
  const [showConfirm, setShowConfirm] = useState(false);
  const { session } = usePaymentContext();
  const isAdmin = ["owner", "admin"].includes(session?.user?.role);
  const {
    data = {
      settings: {},
      active: true
    },
    error,
    run,
    loading
  } = useRequest(
    (forceRender) => fetchDonateSetting(
      {
        mountLocation,
        description,
        defaultSettings,
        active,
        componentDid: window.blocklet?.componentId?.split("/").pop()
      },
      forceRender
    ),
    {
      refreshDeps: [mountLocation],
      onError: (err) => {
        Toast.error(formatError(err));
      }
    }
  );
  const updateSettings = async (newSettings) => {
    try {
      const livemode = localStorage.getItem("livemode") !== "false";
      await api.put(`/api/settings/${mountLocation}`, {
        livemode,
        settings: newSettings
      });
      run(true);
      Toast.success(t("common.saved"));
    } catch (err) {
      Toast.error(formatError(err));
      throw err;
    }
  };
  const supportPaymentKit = getPaymentKitComponent();
  const handleEnable = async () => {
    if (!enableDonate || !data || data?.active) return;
    try {
      await api.put(`/api/settings/${data.id}`, { active: true });
      if (supportPaymentKit) {
        setShowConfirm(true);
      } else {
        Toast.success(t("payment.checkout.donation.enableSuccess"));
        run(true);
      }
    } catch (err) {
      Toast.error(formatError(err));
    }
  };
  if (loading || error) {
    return null;
  }
  return /* @__PURE__ */ jsx(
    Provider,
    {
      value: {
        settings: data,
        refresh: run,
        updateSettings,
        api
      },
      children: data?.active === false ? /* @__PURE__ */ jsxs(Fragment, { children: [
        enableDonate && isAdmin && /* @__PURE__ */ jsxs(Stack, { spacing: 1, sx: { alignItems: "center" }, children: [
          /* @__PURE__ */ jsx(
            Typography,
            {
              sx: {
                color: "text.secondary"
              },
              children: t("payment.checkout.donation.inactive")
            }
          ),
          /* @__PURE__ */ jsx(
            Button,
            {
              size: "small",
              variant: "outlined",
              color: "primary",
              onClick: handleEnable,
              sx: { width: "fit-content" },
              children: t("payment.checkout.donation.enable")
            }
          )
        ] }),
        showConfirm && /* @__PURE__ */ jsx(
          ConfirmDialog,
          {
            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);
              openDonationSettings(false);
              setShowConfirm(false);
            }
          }
        )
      ] }) : children
    }
  );
}
function useDonateContext() {
  const context = useContext(DonateContext);
  return context;
}
export const clearDonateCache = (mountLocation) => {
  const livemode = localStorage.getItem("livemode") !== "false";
  const cacheKey = `donate-settings-${mountLocation}-${livemode}`;
  localStorage.removeItem(cacheKey);
};
export const clearDonateSettings = async (mountLocation) => {
  try {
    const livemode = localStorage.getItem("livemode") !== "false";
    await api.delete(`/api/settings/${mountLocation}`, {
      params: {
        livemode
      }
    });
    clearDonateCache(mountLocation);
  } catch (err) {
    Toast.error(formatError(err));
  }
};
export { DonateContext, DonateProvider, Consumer as DonateConsumer, useDonateContext };
