"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "ActionButton", {
    enumerable: true,
    get: function() {
        return ActionButton;
    }
});
const _jsxruntime = require("react/jsx-runtime");
const _react = require("react");
const _button = /*#__PURE__*/ _interop_require_default(require("../../../button"));
const _statusGuardButton = require("../../../button/statusGuardButton");
const _toast = require("../../../toast");
const _utils = require("@orderly.network/utils");
const _hooks = require("@orderly.network/hooks");
const _modal = require("../../../modal");
const _crossChainConfirm = require("./crossChainConfirm");
const _useChainNotSupport = require("../useChainNotSupport");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
const ActionButton = (props)=>{
    const { chain, chains, onWithdraw, switchChain, disabled, openChainPicker, quantity, loading, chainVaultBalance, maxAmount, crossChainWithdraw, address, fee } = props;
    /// has cross chain withdraw transaction
    const [crossChainTrans, setCrossChainTrans] = (0, _react.useState)(undefined);
    const chainNotSupport = (0, _useChainNotSupport.useChainNotSupport)(chain, chains);
    const { data: assetHistory } = (0, _hooks.usePrivateQuery)("/v1/asset/history", {
        revalidateOnMount: true
    });
    const needCrossChain = (0, _react.useRef)(false);
    (0, _hooks.useWalletSubscription)({
        onMessage (data) {
            if (!crossChainTrans) return;
            ;
            const { trxId, transStatus } = data;
            if (trxId === crossChainTrans && transStatus === "COMPLETED") {
                setCrossChainTrans(undefined);
            }
        }
    });
    (0, _react.useEffect)(()=>{
        // const item = assetHistory?.find((e: any) => e.trans_status === "COMPLETED");
        const item = assetHistory?.find((e)=>e.trans_status === "pending_rebalance".toUpperCase());
        setCrossChainTrans(item);
    }, [
        assetHistory
    ]);
    const warningMessage = (0, _react.useMemo)(()=>{
        const networkName = chain?.info?.network_infos?.name;
        // check has cross chain withdraw
        if (crossChainTrans) {
            return `Your cross-chain withdrawal is being processed...`;
        }
        // check cur chain is support no not
        if (chainNotSupport) {
            if (chains?.length && chains.length > 1) {
                return `Withdrawals are not supported on ${networkName ?? "this chain"}. Please switch to any of the bridgeless networks.`;
            }
            return `Withdrawals are not supported on ${networkName ?? "this chain"}.`;
        }
        // check quantity and vaultBalance
        if (crossChainWithdraw) {
            needCrossChain.current = true;
            return `Withdrawal exceeds the balance of the ${networkName} vault ( ${chainVaultBalance} USDC ). Cross-chain rebalancing fee will be charged for withdrawal to ${networkName}.`;
        }
        return undefined;
    }, [
        chainNotSupport,
        chains,
        chain,
        quantity,
        maxAmount,
        crossChainWithdraw,
        chainVaultBalance
    ]);
    const onClick = (0, _react.useCallback)(()=>{
        const qty = parseFloat(quantity);
        if (crossChainWithdraw) {
            _modal.modal.confirm({
                title: "Confirm to withdraw",
                content: /*#__PURE__*/ (0, _jsxruntime.jsx)(_crossChainConfirm.CrossChainConfirm, {
                    address: address || "",
                    amount: qty - fee,
                    chain: chain
                }),
                onOk: async ()=>{
                    onWithdraw();
                },
                onCancel: async ()=>{}
            });
        } else {
            onWithdraw();
        }
    }, [
        crossChainWithdraw,
        quantity,
        fee
    ]);
    const swtichChain = (chainId)=>{
        _toast.toast.promise(switchChain({
            chainId: (0, _utils.int2hex)(chainId)
        }), {
            loading: "Loading",
            success: (data)=>`Successfully`,
            error: (err)=>`Error: ${err.toString()}`
        });
    };
    const actionButton = (0, _react.useMemo)(()=>{
        if (!chainNotSupport) {
            return /*#__PURE__*/ (0, _jsxruntime.jsx)(_statusGuardButton.StatusGuardButton, {
                children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_button.default, {
                    id: "orderly-withdraw-confirm-button",
                    className: "desktop:orderly-text-xs",
                    fullWidth: true,
                    onClick: onClick,
                    disabled: props.disabled || props.loading || crossChainTrans !== undefined,
                    loading: loading,
                    children: "Withdraw"
                })
            });
        }
        return /*#__PURE__*/ (0, _jsxruntime.jsx)(_button.default, {
            id: "orderly-withdraw-confirm-button",
            className: "desktop:orderly-text-xs",
            fullWidth: true,
            onClick: ()=>{
                openChainPicker?.().then(({ id })=>{
                    id && swtichChain(id);
                });
            },
            children: "Switch network"
        });
    }, [
        chainNotSupport,
        chains,
        switchChain,
        disabled,
        chain,
        quantity,
        loading
    ]);
    return /*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, {
        children: [
            /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
                className: "orderly-withdraw-warning-message",
                children: [
                    warningMessage && /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {
                        className: "orderly-warning-msg orderly-text-warning orderly-text-4xs orderly-text-center orderly-px-[20px] orderly-pt-4 orderly-pb-3 desktop:orderly-text-2xs",
                        children: warningMessage
                    }),
                    " "
                ]
            }),
            /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {
                className: "orderly-flex orderly-justify-center orderly-text-xs desktop:orderly-text-xs orderly-font-bold",
                children: /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {
                    className: "orderly-withdraw-action-button-container orderly-w-full",
                    children: actionButton
                })
            })
        ]
    });
};

//# sourceMappingURL=actionButton.js.map