"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "DepositForm", {
    enumerable: true,
    get: function() {
        return DepositForm;
    }
});
const _jsxruntime = require("react/jsx-runtime");
const _react = require("react");
const _quantityInput = require("../../block/quantityInput");
const _walletPicker = require("../pickers/walletPicker");
const _divider = require("../../divider");
const _tokenQtyInput = require("../../input/tokenQtyInput");
const _summary = require("../../block/deposit/sections/summary");
const _networkImage = require("../../icon/networkImage");
const _icon = require("../../icon");
const _actionButton = require("./sections/actionButton");
const _utils = require("@orderly.network/utils");
const _toast = require("../../toast");
const _num = require("../../utils/num");
const _provider = require("../../provider");
const _logo = require("../../logo");
const DepositForm = (props)=>{
    const { maxAmount, walletName, address, chains, chain, dst, switchChain, onOk, isNativeToken, quantity, setQuantity, depositFee } = props;
    const { errors, brokerName, customChains } = (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 [tokens, setTokens] = (0, _react.useState)([]);
    const cleanData = ()=>{
        setQuantity("");
    };
    const onDirectDeposit = (0, _react.useCallback)(()=>{
        props.deposit().then((res)=>{
            setQuantity("");
            _toast.toast.success("Deposit requested");
            onOk?.(res);
        }).catch((error)=>{
            _toast.toast.error(error.message || error.errorCode || "Deposit failed");
        }).finally(()=>{
            setSubmitting(false);
        });
    }, [
        props.deposit
    ]);
    const onDeposit = (0, _react.useCallback)(()=>{
        const num = Number(quantity);
        if (!props.token) {
            _toast.toast.error("Please select a token");
            return;
        }
        if (isNaN(num) || num <= 0) {
            _toast.toast.error("Please input a valid number");
            return;
        }
        if (inputStatus !== "default") {
            return;
        }
        if (submitting) return;
        setSubmitting(true);
        onDirectDeposit();
    }, [
        quantity,
        submitting,
        onDirectDeposit
    ]);
    const onApprove = (0, _react.useCallback)(async ()=>{
        return props.approve(quantity);
    }, [
        quantity,
        props.approve
    ]);
    const onValueChange = (0, _react.useCallback)((value)=>{
        if (value.value === ".") {
            setQuantity("0.");
            return;
        }
        const result = value.value.match(_num.NumberReg);
        if (Array.isArray(result)) {
            value = result[0];
            if (isNaN(parseFloat(value))) {
                setQuantity("");
            } else {
                let d = new _utils.Decimal(value);
                if (d.dp() > dst.decimals) {
                    setQuantity(d.todp(Math.min(dst.decimals, 8)).toString());
                } else {
                    setQuantity(value);
                }
                if (d.gt(maxAmount)) {
                    setInputStatus("error");
                    setHintMessage("Insufficient balance");
                } else {
                    // reset input status
                    setInputStatus("default");
                    setHintMessage("");
                }
            }
        } else {
            setQuantity("");
            // reset input status when value is empty
            setInputStatus("default");
            setHintMessage("");
        }
    }, [
        dst.decimals,
        maxAmount
    ]);
    const onTokenChange = (token)=>{
        cleanData();
        props.switchToken?.(token);
    };
    const onChainChange = (0, _react.useCallback)((value)=>{
        if (!value) return;
        if (value.network_infos?.chain_id === chain?.id) return Promise.resolve();
        props.switchChain?.({
            chainId: (0, _utils.int2hex)(Number(value.network_infos?.chain_id)),
            rpcUrl: value.network_infos?.public_rpc_url,
            token: value.network_infos?.currency_symbol,
            // name: chain.network_infos?.name,
            label: value.network_infos?.name
        }).then((switched)=>{
            if (!switched) {
                _toast.toast.error("Switch chain failed");
                return;
            }
            // switch success，set tokens list
            setTokens(value?.token_infos ?? []);
            // switch chain need to update chain token
            const token = getTokenByTokenList(value?.token_infos);
            if (token) {
                props.switchToken?.(token);
            }
            _toast.toast.success("Network switched");
            cleanData();
        }).catch((error)=>{
            _toast.toast.error(`Switch chain failed: ${error.message}`);
        });
    }, [
        props.switchChain,
        chain,
        props.token?.symbol
    ]);
    const getTokenByTokenList = (tokens = [])=>{
        const tokenObj = tokens.reduce((acc, item)=>{
            acc[item.symbol] = item;
            return acc;
        }, {});
        const token = tokenObj["USDC"] || tokenObj["USDbC"] || tokens[0];
        return token;
    };
    // when chain changed and chain data ready then call this function
    const onChainInited = (0, _react.useCallback)((chain)=>{
        if (chain && chain.token_infos?.length > 0) {
            const tokens = chain.token_infos;
            const token = getTokenByTokenList(tokens);
            if (!token || props.token?.symbol === token.symbol) return;
            setTokens(tokens);
            if (!token) return;
            props.switchToken?.(token);
        }
    }, [
        props.token?.symbol
    ]);
    (0, _react.useEffect)(()=>{
        // check quantity
        if (isNaN(Number(quantity)) || !quantity) return;
        const d = new _utils.Decimal(quantity);
        if (d.gt(maxAmount)) {
            setInputStatus("error");
            setHintMessage("Insufficient balance");
        } else {
            setInputStatus("default");
            setHintMessage("");
        }
    }, [
        maxAmount
    ]);
    return /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
        id: "orderly-deposit-form",
        children: [
            /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
                className: "orderly-flex orderly-items-center orderly-py-2",
                children: [
                    /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {
                        className: "orderly-flex-1 orderly-text-2xs desktop:orderly-text-base orderly-text-base-con",
                        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-pb-2",
                children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_walletPicker.WalletPicker, {
                    address: address,
                    chain: chain,
                    settingChain: props.settingChain,
                    onChainChange: onChainChange,
                    onChainInited: onChainInited,
                    chains: customChains
                })
            }),
            /*#__PURE__*/ (0, _jsxruntime.jsx)(_quantityInput.QuantityInput, {
                tokens: tokens,
                // src token use display_name
                // Mantle chain: USDC.e → USDC
                token: props.token ? {
                    ...props.token,
                    symbol: props.token.display_name || props.token.symbol
                } : props.token,
                quantity: quantity,
                markPrice: 1,
                maxAmount: Number(maxAmount),
                onValueChange: onValueChange,
                status: inputStatus,
                decimals: dst.decimals,
                hintMessage: hintMessage,
                fetchBalance: props.fetchBalance,
                onTokenChange: onTokenChange,
                balanceRevalidating: props.balanceRevalidating,
                disabled: errors?.ChainNetworkNotSupport
            }),
            /*#__PURE__*/ (0, _jsxruntime.jsx)(_divider.Divider, {
                className: "orderly-py-4",
                children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_icon.MoveDownIcon, {
                    className: "orderly-text-primary-light"
                })
            }),
            /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
                className: "orderly-flex orderly-py-2",
                children: [
                    /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {
                        className: "orderly-flex-1 orderly-text-2xs orderly-text-base-contrast desktop:orderly-text-base",
                        children: "Your " + brokerName + " account"
                    }),
                    /*#__PURE__*/ (0, _jsxruntime.jsx)(_logo.Logo.secondary, {
                        size: 24
                    })
                ]
            }),
            /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {
                className: "orderly-py-2",
                children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_tokenQtyInput.TokenQtyInput, {
                    token: dst,
                    amount: quantity,
                    loading: false,
                    readOnly: true,
                    fee: 0
                })
            }),
            /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {
                className: "orderly-flex orderly-items-start orderly-py-3 orderly-text-3xs orderly-text-tertiary",
                children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_summary.Summary, {
                    nativeToken: chain?.info?.nativeToken,
                    src: props.token,
                    dst: dst,
                    price: 1,
                    depositFee: depositFee
                })
            }),
            /*#__PURE__*/ (0, _jsxruntime.jsx)(_actionButton.ActionButton, {
                chain: chain,
                chains: chains,
                token: props.token,
                onDeposit: onDeposit,
                allowance: props.isNativeToken ? Number.MAX_VALUE : Number(props.allowance),
                chainNotSupport: !!errors?.ChainNetworkNotSupport,
                disabled: !quantity || inputStatus === "error" || props.depositFeeRevalidating,
                loading: submitting || props.depositFeeRevalidating,
                submitting: submitting || props.depositFeeRevalidating,
                switchChain: switchChain,
                quantity: quantity,
                onApprove: onApprove,
                maxQuantity: maxAmount,
                warningMessage: "",
                onChainChange: onChainChange
            })
        ]
    });
};

//# sourceMappingURL=depositForm.js.map