import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useMemo, useState, useRef, useCallback } from "react";
import Button from "../../../button";
import { toast } from "../../../toast";
import { int2hex } from "@orderly.network/utils";
import { usePrivateQuery, useWalletSubscription } from "@orderly.network/hooks";
import { modal } from "../../../modal";
import { CrossChainConfirm } from "./crossChainConfirm";
import { useChainNotSupport } from "../useChainNotSupport";
import { StatusGuardButton } from "../../../block/accountStatus";
export 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] = useState(undefined);
    const chainNotSupport = useChainNotSupport(chain, chains);
    const { data: assetHistory } = usePrivateQuery("/v1/asset/history", {
        revalidateOnMount: true
    });
    const needCrossChain = useRef(false);
    useWalletSubscription({
        onMessage (data) {
            if (!crossChainTrans) return;
            ;
            const { trxId, transStatus } = data;
            if (trxId === crossChainTrans && transStatus === "COMPLETED") {
                setCrossChainTrans(undefined);
            }
        }
    });
    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 = 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 = useCallback(()=>{
        const qty = parseFloat(quantity);
        if (crossChainWithdraw) {
            modal.confirm({
                title: "Confirm to withdraw",
                content: /*#__PURE__*/ _jsx(CrossChainConfirm, {
                    address: address || "",
                    amount: qty - fee,
                    chain: chain
                }),
                onOk: async ()=>{
                    onWithdraw();
                },
                onCancel: async ()=>{}
            });
        } else {
            onWithdraw();
        }
    }, [
        crossChainWithdraw,
        quantity,
        fee
    ]);
    const swtichChain = (chainId)=>{
        toast.promise(switchChain({
            chainId: int2hex(chainId)
        }), {
            loading: "Loading",
            success: (data)=>`Successfully`,
            error: (err)=>`Error: ${err.toString()}`
        });
    };
    const actionButton = useMemo(()=>{
        if (!chainNotSupport) {
            return /*#__PURE__*/ _jsx(StatusGuardButton, {
                children: /*#__PURE__*/ _jsx(Button, {
                    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__*/ _jsx(Button, {
            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__*/ _jsxs(_Fragment, {
        children: [
            /*#__PURE__*/ _jsxs("div", {
                className: "orderly-withdraw-warning-message",
                children: [
                    warningMessage && /*#__PURE__*/ _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__*/ _jsx("div", {
                className: "orderly-flex orderly-justify-center orderly-text-xs desktop:orderly-text-xs orderly-font-bold",
                children: /*#__PURE__*/ _jsx("div", {
                    className: "orderly-withdraw-action-button-container orderly-w-full",
                    children: actionButton
                })
            })
        ]
    });
};

//# sourceMappingURL=actionButton.js.map