"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _jsxRuntime = require("react/jsx-runtime");
var _react = require("react");
var _material = require("@mui/material");
var _context = require("@arcblock/ux/lib/Locale/context");
var _Toast = _interopRequireDefault(require("@arcblock/ux/lib/Toast"));
var _ufo = require("ufo");
var _ahooks = require("ahooks");
var _dialog = _interopRequireDefault(require("@arcblock/ux/lib/Dialog/dialog"));
var _payment = require("../contexts/payment");
var _util = require("../libs/util");
var _api = _interopRequireDefault(require("../libs/api"));
var _loadingButton = _interopRequireDefault(require("./loading-button"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const fetchSubscriptionDetail = async params => {
  const url = `/api/subscriptions/${params.subscriptionId}`;
  const res = await _api.default.get(params.authToken ? (0, _ufo.joinURL)(url, `?authToken=${params.authToken}`) : url);
  return res.data;
};
const fetchRecoverInfo = async params => {
  const url = `/api/subscriptions/${params.subscriptionId}/recover-info`;
  const res = await _api.default.get(params.authToken ? (0, _ufo.joinURL)(url, `?authToken=${params.authToken}`) : url);
  return res.data;
};
const recoverSubscription = async params => {
  const url = `/api/subscriptions/${params.subscriptionId}/recover`;
  const res = await _api.default.put(params.authToken ? (0, _ufo.joinURL)(url, `?authToken=${params.authToken}`) : url);
  return res.data;
};
function RecoverSubscription({
  subscriptionId,
  dialogProps = {
    open: true
  },
  onResumed = () => {},
  successToast = true,
  authToken = void 0
}) {
  const {
    t,
    locale
  } = (0, _context.useLocaleContext)();
  const {
    connect
  } = (0, _payment.usePaymentContext)();
  const [recoverLoading, setRecoverLoading] = (0, _react.useState)(false);
  const [dialogOpen, setDialogOpen] = (0, _react.useState)(dialogProps.open || false);
  const {
    data,
    error,
    loading
  } = (0, _ahooks.useRequest)(() => fetchRecoverInfo({
    subscriptionId,
    authToken
  }), {
    ready: !!subscriptionId
  });
  const isCrossOriginRequest = (0, _util.isCrossOrigin)();
  const needStake = data?.needStake ?? false;
  const handleSuccess = async () => {
    try {
      const subscription = await fetchSubscriptionDetail({
        subscriptionId,
        authToken
      });
      if (successToast) {
        _Toast.default.success(t("payment.customer.recover.success"));
      }
      setDialogOpen(false);
      onResumed(subscription);
      setRecoverLoading(false);
    } catch (err) {
      console.error("Failed to fetch updated subscription:", err);
      _Toast.default.error((0, _util.formatError)(err));
      setRecoverLoading(false);
    }
  };
  const handleRecoverWithStake = () => {
    setRecoverLoading(true);
    try {
      connect.open({
        locale,
        containerEl: void 0,
        saveConnect: false,
        action: "re-stake",
        prefix: (0, _ufo.joinURL)((0, _util.getPrefix)(), "/api/did"),
        useSocket: !isCrossOriginRequest,
        extraParams: {
          subscriptionId
        },
        messages: {
          scan: t("common.connect.defaultScan"),
          title: t("payment.customer.recover.reStakeTitle"),
          confirm: t("common.connect.confirm")
        },
        onSuccess: handleSuccess,
        onClose: () => {
          connect.close();
          setRecoverLoading(false);
        },
        onError: err => {
          _Toast.default.error((0, _util.formatError)(err));
          setRecoverLoading(false);
        }
      });
    } catch (err) {
      _Toast.default.error((0, _util.formatError)(err));
      setRecoverLoading(false);
    }
  };
  const handleDirectRecover = async () => {
    setRecoverLoading(true);
    try {
      const result = await recoverSubscription({
        subscriptionId,
        authToken
      });
      if (result.needStake) {
        handleRecoverWithStake();
        return;
      }
      const {
        subscription
      } = result;
      if (successToast) {
        _Toast.default.success(t("payment.customer.recover.success"));
      }
      setDialogOpen(false);
      onResumed(subscription);
      setRecoverLoading(false);
    } catch (err) {
      _Toast.default.error((0, _util.formatError)(err));
      setRecoverLoading(false);
    }
  };
  const handleRecover = () => {
    if (needStake) {
      handleRecoverWithStake();
    } else {
      handleDirectRecover();
    }
  };
  const handleClose = () => {
    setDialogOpen(false);
    dialogProps.onClose?.();
  };
  if (loading) {
    return null;
  }
  return /* @__PURE__ */(0, _jsxRuntime.jsx)(_dialog.default, {
    PaperProps: {
      style: {
        minHeight: "auto"
      }
    },
    ...(dialogProps || {}),
    open: dialogOpen,
    title: dialogProps?.title || t("payment.customer.recover.title"),
    sx: {
      "& .MuiDialogContent-root": {
        pt: 0
      }
    },
    onClose: handleClose,
    children: error ? /* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Alert, {
      severity: "error",
      children: error.message
    }) : /* @__PURE__ */(0, _jsxRuntime.jsxs)(_material.Stack, {
      sx: {
        gap: 2
      },
      children: [/* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Typography, {
        variant: "body2",
        sx: {
          color: "text.secondary"
        },
        children: t("payment.customer.recover.description", {
          date: (0, _util.formatToDate)(Number(data?.subscription?.current_period_end || "0") * 1e3)
        })
      }), needStake && /* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Alert, {
        severity: "warning",
        children: t("payment.customer.recover.stakeRequiredDescription")
      }), /* @__PURE__ */(0, _jsxRuntime.jsxs)(_material.Stack, {
        direction: "row",
        sx: {
          justifyContent: "flex-end",
          gap: 2,
          mt: 2
        },
        children: [/* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Button, {
          variant: "outlined",
          color: "primary",
          onClick: handleClose,
          children: t("common.cancel")
        }), /* @__PURE__ */(0, _jsxRuntime.jsx)(_loadingButton.default, {
          variant: "contained",
          size: "small",
          loading: recoverLoading,
          onClick: handleRecover,
          children: t("common.confirm")
        })]
      })]
    })
  });
}
module.exports = RecoverSubscription;