"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "WithdrawForm", {
    enumerable: true,
    get: function() {
        return WithdrawForm;
    }
});
const _jsxruntime = require("react/jsx-runtime");
const _react = require("react");
const _divider = require("../../divider");
const _icon = require("../../icon");
const _quantityInput = require("../../block/quantityInput");
const _tokenQtyInput = require("../../input/tokenQtyInput");
const _summary = require("../../block/withdraw/sections/summary");
const _walletPicker = require("../pickers/walletPicker");
const _css = require("../../utils/css");
const _networkImage = require("../../icon/networkImage");
const _types = require("@orderly.network/types");
const _toast = require("../../toast");
const _utils = require("@orderly.network/utils");
const _actionButton = require("./sections/actionButton");
const _settledInfo = require("./sections/settledInfo");
const _chainDialog = require("../pickers/chainPicker/chainDialog");
const _modal = require("../../modal");
const _provider = require("../../provider");
const _logo = require("../../logo");
const _hooks = require("@orderly.network/hooks");
const numberReg = /^([0-9]{1,}[.]?[0-9]*)/;
const WithdrawForm = ({ dst, status = _types.WithdrawStatus.Normal, chains, chain, decimals, address, walletName, minAmount, availableBalance, unsettledPnL, hasPositions, maxAmount, onWithdraw, onOk, switchChain })=>{
    const { brokerName } = (0, _react.useContext)(_provider.OrderlyAppContext);
    const [inputStatus, setInputStatus] = (0, _react.useState)("default");
    const [hintMessage, setHintMessage] = (0, _react.useState)();
    const [submitting, setSubmitting] = (0, _react.useState)(false);
    const [quantity, setQuantity] = (0, _react.useState)("");
    // @ts-ignore
    const { data: balanceList } = (0, _hooks.useQuery)(`/v1/public/vault_balance`, {
        revalidateOnMount: true
    });
    const chainVaultBalance = (0, _react.useMemo)(()=>{
        if (!balanceList || !chain) return null;
        // chain.id
        const vaultBalance = balanceList.find((item)=>parseInt(item.chain_id) === chain?.id);
        if (vaultBalance) {
            return vaultBalance.balance;
        }
        return null;
    }, [
        chains,
        chain,
        balanceList
    ]);
    // console.log("vault_balance data", balanceList, chain, chains, chainVaultBalance);
    const openChainPicker = (0, _react.useCallback)(async ()=>{
        const result = await _modal.modal.show(_chainDialog.ChainDialog, {
            testChains: chains,
            currentChainId: chain?.id
        });
        return {
            id: result?.id,
            name: result?.name
        };
    }, [
        chains,
        chain
    ]);
    const onChainChange = (0, _react.useCallback)((value)=>{
        if (value.network_infos?.chain_id === chain?.id) return Promise.resolve();
        switchChain?.({
            chainId: (0, _utils.int2hex)(Number(value.network_infos?.chain_id))
        }).then((switched)=>{
            if (!switched) {
                _toast.toast.error("Switch chain failed");
                return;
            }
            _toast.toast.success("Network switched");
            // clear data
            setQuantity("");
        }, (error)=>{
            //
            _toast.toast.error(`Switch chain failed: ${error.message}`);
        });
    }, [
        switchChain,
        chain
    ]);
    const crossChainWithdraw = (0, _react.useMemo)(()=>{
        if (chainVaultBalance !== null) {
            const qtyNum = parseFloat(quantity);
            const value = qtyNum > chainVaultBalance && qtyNum <= maxAmount;
            return value;
        }
        return false;
    }, [
        quantity,
        maxAmount,
        chainVaultBalance
    ]);
    const doWithdraw = (0, _react.useCallback)(()=>{
        if (submitting) return;
        const num = Number(quantity);
        if (num < minAmount) {
            _toast.toast.error(`quantity must large than ${minAmount}`);
            return;
        }
        if (inputStatus !== "default") {
            return;
        }
        if (!chain || !chain.id) {
            throw new Error("chain is not set");
        }
        setSubmitting(true);
        return onWithdraw({
            amount: quantity,
            token: "USDC",
            chainId: chain?.id,
            allowCrossChainWithdraw: crossChainWithdraw
        }).then((res)=>{
            _toast.toast.success("Withdrawal requested");
            setQuantity("");
            onOk?.(res);
        }, (error)=>{
            _toast.toast.error(error.message);
        }).finally(()=>{
            setSubmitting(false);
        });
    }, [
        quantity,
        minAmount,
        inputStatus,
        chain?.id,
        submitting,
        onOk,
        crossChainWithdraw
    ]);
    const onValueChange = (0, _react.useCallback)((value)=>{
        if (value.value === ".") {
            setQuantity("0.");
            return;
        }
        const result = value.value.match(numberReg);
        if (Array.isArray(result)) {
            value = result[0];
            // value = parseFloat(value);
            if (isNaN(parseFloat(value))) {
                setQuantity("");
            } else {
                let d = new _utils.Decimal(value);
                // setQuantity(value);
                if (d.dp() > decimals) {
                    setQuantity(d.todp(Math.min(decimals, 8)).toString());
                } else {
                    setQuantity(value);
                }
            }
        } else {
            setQuantity("");
        }
    }, [
        decimals
    ]);
    const fee = (0, _react.useMemo)(()=>{
        if (!chain) return 0;
        const item = chains?.find((c)=>c.chain_id === chain.id);
        if (!item) {
            return 0;
        }
        if (crossChainWithdraw) {
            return(// @ts-ignore
            (item.withdrawal_fee || 0) + (item.cross_chain_withdrawal_fee || 0));
        }
        return item.withdrawal_fee || 0;
    }, [
        chain,
        chains,
        crossChainWithdraw
    ]);
    (0, _react.useEffect)(()=>{
        // const num = Number(quantity);
        // if (num > maxAmount) {
        //   if (num <= availableBalance) {
        //     setInputStatus("warning");
        //     setHintMessage("Please settle your balance");
        //   } else {
        //     setInputStatus("error");
        //     setHintMessage("Insufficient balance");
        //   }
        // } else {
        //   setInputStatus("default");
        //   setHintMessage(undefined);
        // }
        const input = Number(quantity);
        const freeCollateral = maxAmount;
        if (unsettledPnL < 0) {
            if (input > freeCollateral) {
                setInputStatus("error");
                setHintMessage("Insufficient balance");
            } else {
                setInputStatus("default");
                setHintMessage(undefined);
            }
        } else {
            if (input > freeCollateral) {
                setInputStatus("error");
                setHintMessage("Insufficient balance");
            } else if (input > freeCollateral - unsettledPnL && input <= freeCollateral) {
                setInputStatus("warning");
                setHintMessage("Please settle your balance");
            } else {
                setInputStatus("default");
                setHintMessage(undefined);
            }
        }
    }, [
        quantity,
        maxAmount,
        availableBalance
    ]);
    return /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
        id: "orderly-withdraw-form",
        children: [
            /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
                className: "orderly-flex orderly-items-center orderly-py-2 orderly-text-2xs orderly-text-base-contrast desktop:orderly-text-base",
                children: [
                    /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {
                        className: "orderly-flex-1",
                        children: "Your " + brokerName + " account"
                    }),
                    /*#__PURE__*/ (0, _jsxruntime.jsx)(_logo.Logo.secondary, {
                        size: 24
                    })
                ]
            }),
            /*#__PURE__*/ (0, _jsxruntime.jsx)(_quantityInput.QuantityInput, {
                tokens: [],
                // @ts-ignore
                token: {
                    symbol: "USDC",
                    decimals: 6
                },
                decimals: decimals,
                status: inputStatus,
                className: (0, _css.cn)(status !== _types.WithdrawStatus.Normal && "orderly-outline orderly-outline-1", {
                    "orderly-outline-trade-loss": status === _types.WithdrawStatus.InsufficientBalance,
                    "orderly-outline-yellow-500": status === _types.WithdrawStatus.Unsettle
                }),
                quantity: quantity,
                onValueChange: onValueChange,
                maxAmount: maxAmount,
                hintMessage: hintMessage,
                markPrice: 1
            }),
            /*#__PURE__*/ (0, _jsxruntime.jsx)(_settledInfo.UnsettledInfo, {
                unsettledPnL: unsettledPnL,
                hasPositions: hasPositions
            }),
            /*#__PURE__*/ (0, _jsxruntime.jsx)(_divider.Divider, {
                className: "orderly-py-3",
                children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_icon.MoveDownIcon, {
                    className: "orderly-text-primary-light"
                })
            }),
            /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
                className: "orderly-flex orderly-items-center orderly-text-2xs desktop:orderly-text-base",
                children: [
                    /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {
                        className: "orderly-flex-1",
                        children: "Your web3 wallet"
                    }),
                    /*#__PURE__*/ (0, _jsxruntime.jsx)(_networkImage.NetworkImage, {
                        type: typeof walletName === "undefined" ? "placeholder" : "wallet",
                        name: walletName,
                        rounded: true
                    })
                ]
            }),
            /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {
                className: "orderly-py-2",
                children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_walletPicker.WalletPicker, {
                    address: address,
                    chain: chain,
                    onChainChange: onChainChange
                })
            }),
            /*#__PURE__*/ (0, _jsxruntime.jsx)(_tokenQtyInput.TokenQtyInput, {
                amount: quantity,
                fee: fee,
                needCalc: true,
                token: dst
            }),
            /*#__PURE__*/ (0, _jsxruntime.jsx)(_summary.Summary, {
                fee: fee
            }),
            /*#__PURE__*/ (0, _jsxruntime.jsx)(_actionButton.ActionButton, {
                chains: chains,
                chain: chain,
                onWithdraw: doWithdraw,
                disabled: !quantity || Number(quantity) - fee <= 0 || Number(quantity) > maxAmount,
                switchChain: switchChain,
                quantity: quantity,
                loading: submitting,
                openChainPicker: openChainPicker,
                chainVaultBalance: chainVaultBalance,
                maxAmount: maxAmount,
                crossChainWithdraw: crossChainWithdraw,
                address: address,
                fee: fee
            })
        ]
    });
};

//# sourceMappingURL=withdrawForm.js.map