import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useContext, useEffect, useState } from "react";
import { QuantityInput } from "../../block/quantityInput";
import { WalletPicker } from "../pickers/walletPicker";
import { Divider } from "../../divider";
import { TokenQtyInput } from "../../input/tokenQtyInput";
import { Summary } from "../../block/deposit/sections/summary";
import { NetworkImage } from "../../icon/networkImage";
import { MoveDownIcon } from "../../icon";
import { ActionButton } from "./sections/actionButton";
import { Decimal, int2hex } from "@orderly.network/utils";
import { toast } from "../../toast";
import { NumberReg } from "../../utils/num";
import { OrderlyAppContext } from "../../provider";
import { Logo } from "../../logo";
export const DepositForm = (props)=>{
    const { maxAmount, walletName, address, chains, chain, dst, switchChain, onOk, isNativeToken, quantity, setQuantity, depositFee } = props;
    const { errors, brokerName, customChains } = useContext(OrderlyAppContext);
    const [inputStatus, setInputStatus] = useState("default");
    const [hintMessage, setHintMessage] = useState();
    const [submitting, setSubmitting] = useState(false);
    const [tokens, setTokens] = useState([]);
    const cleanData = ()=>{
        setQuantity("");
    };
    const onDirectDeposit = useCallback(()=>{
        props.deposit().then((res)=>{
            setQuantity("");
            toast.success("Deposit requested");
            onOk?.(res);
        }).catch((error)=>{
            toast.error(error?.errorCode || "Deposit failed");
        }).finally(()=>{
            setSubmitting(false);
        });
    }, [
        props.deposit
    ]);
    const onDeposit = useCallback(()=>{
        const num = Number(quantity);
        if (!props.token) {
            toast.error("Please select a token");
            return;
        }
        if (isNaN(num) || num <= 0) {
            toast.error("Please input a valid number");
            return;
        }
        if (inputStatus !== "default") {
            return;
        }
        if (submitting) return;
        setSubmitting(true);
        onDirectDeposit();
    }, [
        quantity,
        submitting,
        onDirectDeposit
    ]);
    const onApprove = useCallback(async ()=>{
        return props.approve(quantity);
    }, [
        quantity,
        props.approve
    ]);
    const onValueChange = useCallback((value)=>{
        if (value.value === ".") {
            setQuantity("0.");
            return;
        }
        const result = value.value.match(NumberReg);
        if (Array.isArray(result)) {
            value = result[0];
            if (isNaN(parseFloat(value))) {
                setQuantity("");
            } else {
                let d = new 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 = useCallback((value)=>{
        if (!value) return;
        if (value.network_infos?.chain_id === chain?.id) return Promise.resolve();
        props.switchChain?.({
            chainId: 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(()=>{
            // switch success，set tokens list
            setTokens(value?.token_infos ?? []);
            toast.success("Network switched");
            cleanData();
        }).catch((error)=>{
            toast.error(`Switch chain failed: ${error.message}`);
        });
    }, [
        props.switchChain,
        chain
    ]);
    // when chain changed and chain data ready then call this function
    const onChainInited = useCallback((chain)=>{
        if (chain && chain.token_infos?.length > 0) {
            const tokens = chain.token_infos;
            const tokenObj = tokens.reduce((acc, item)=>{
                acc[item.symbol] = item;
                return acc;
            }, {});
            const token = tokenObj["USDC"] || tokenObj["USDbC"] || tokens[0];
            if (!token || props.token?.symbol === token.symbol) return;
            setTokens(tokens);
            if (!token) return;
            props.switchToken?.(token);
        }
    }, [
        props.token?.symbol
    ]);
    useEffect(()=>{
        // check quantity
        if (isNaN(Number(quantity)) || !quantity) return;
        const d = new Decimal(quantity);
        if (d.gt(maxAmount)) {
            setInputStatus("error");
            setHintMessage("Insufficient balance");
        } else {
            setInputStatus("default");
            setHintMessage("");
        }
    }, [
        maxAmount
    ]);
    return /*#__PURE__*/ _jsxs("div", {
        id: "orderly-deposit-form",
        children: [
            /*#__PURE__*/ _jsxs("div", {
                className: "orderly-flex orderly-items-center orderly-py-2",
                children: [
                    /*#__PURE__*/ _jsx("div", {
                        className: "orderly-flex-1 orderly-text-2xs desktop:orderly-text-base orderly-text-base-con",
                        children: "Your web3 wallet"
                    }),
                    /*#__PURE__*/ _jsx(NetworkImage, {
                        type: typeof walletName === "undefined" ? "placeholder" : "wallet",
                        name: walletName,
                        rounded: true
                    })
                ]
            }),
            /*#__PURE__*/ _jsx("div", {
                className: "orderly-pb-2",
                children: /*#__PURE__*/ _jsx(WalletPicker, {
                    address: address,
                    chain: chain,
                    settingChain: props.settingChain,
                    onChainChange: onChainChange,
                    onChainInited: onChainInited,
                    chains: customChains
                })
            }),
            /*#__PURE__*/ _jsx(QuantityInput, {
                tokens: tokens,
                token: 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__*/ _jsx(Divider, {
                className: "orderly-py-4",
                children: /*#__PURE__*/ _jsx(MoveDownIcon, {
                    className: "orderly-text-primary-light"
                })
            }),
            /*#__PURE__*/ _jsxs("div", {
                className: "orderly-flex orderly-py-2",
                children: [
                    /*#__PURE__*/ _jsx("div", {
                        className: "orderly-flex-1 orderly-text-2xs orderly-text-base-contrast desktop:orderly-text-base",
                        children: "Your " + brokerName + " account"
                    }),
                    /*#__PURE__*/ _jsx(Logo.secondary, {
                        size: 24
                    })
                ]
            }),
            /*#__PURE__*/ _jsx("div", {
                className: "orderly-py-2",
                children: /*#__PURE__*/ _jsx(TokenQtyInput, {
                    token: dst,
                    amount: quantity,
                    loading: false,
                    readOnly: true,
                    fee: 0
                })
            }),
            /*#__PURE__*/ _jsx("div", {
                className: "orderly-flex orderly-items-start orderly-py-3 orderly-text-3xs orderly-text-tertiary",
                children: /*#__PURE__*/ _jsx(Summary, {
                    nativeToken: chain?.info?.nativeToken,
                    src: props.token,
                    dst: dst,
                    price: 1,
                    depositFee: depositFee
                })
            }),
            /*#__PURE__*/ _jsx(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