import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import React from "react";
import { t } from "ttag";
import { useEthereum } from "../../../contexts/ethereum";
import { useAssets } from "../../../contexts/polkadot/assets";
import { safeToFixed } from "../../../format";
import { currentTheme } from "../../../theme";
import Accordion from "../../accordion";
import Button from "../../button";
import { EthConnect } from "../../eth/connect";
import { Box, Row } from "../../grid";
import Icons from "../../icons";
import Space from "../../space";
import { FirstDepositDetails } from "../../sidebar/deposit";
import TextBase from "../../text";
import { Signed } from "./icons";
import { useERC20Deposit, useWrappedETH } from "./hooks";
import { ButtonWrapper } from "./styled";
const WrapETH = ({ 
// amount,
nativeToken, ethBalance, tokenAddress, updateBalance, onSuccess, onError, deposit, onCopy, wrapAmount, wrapBalance, }) => {
    const [pending, setPending] = React.useState(false);
    const wrap = React.useCallback(async () => {
        if (pending) {
            return;
        }
        if (!ethBalance?.gte(wrapAmount ?? 0)) {
            throw new Error("low balance");
        }
        if (wrapAmount?.gte(0)) {
            setPending(true);
            try {
                const tx = await deposit(wrapAmount.toString(10));
                await updateBalance();
                onSuccess?.(tx);
                return tx;
            }
            catch (e) {
                if (e instanceof Error) {
                    console.warn(e.message);
                    onError?.(e);
                }
            }
            finally {
                setPending(false);
            }
        }
        else {
            throw new Error("invalid wrap amount");
        }
    }, [
        wrapAmount,
        ethBalance,
        deposit,
        pending,
        updateBalance,
        onError,
        onSuccess,
    ]);
    return (_jsxs(_Fragment, { children: [_jsxs(Box, { m: "0 0 16px 0", children: [_jsx(TextBase.F2, { children: t `Wrap ${nativeToken.toUpperCase()} to w${nativeToken.toUpperCase()}` }), _jsxs(Box, { p: "16px 12px", style: {
                            border: `1px solid ${currentTheme.colors.border}`,
                            background: currentTheme.colors.pageBackground,
                            borderRadius: 4,
                        }, children: [wrapBalance && wrapBalance.gt(0) && (_jsxs(Row, { spaceBetween: true, style: {
                                    borderBottom: `1px solid ${currentTheme.colors.border}`,
                                    paddingBottom: "4px",
                                    marginBottom: "12px",
                                }, children: [_jsx(TextBase.F2, { gray: true, children: t `w${nativeToken.toUpperCase()} balance` }), _jsx(TextBase.F2, { gray: true, children: wrapBalance?.dp(9).toString() })] })), _jsx(Row, { children: _jsx(TextBase.F2, { children: t `You need to wrap` }) }), _jsx(Box, { m: "0 0 8px 0", children: _jsxs(Row, { justifyContent: "space-between", alignItems: "center", style: {
                                        height: "48px",
                                        background: currentTheme.colors.pale,
                                        borderRadius: "4px",
                                        padding: "0 16px",
                                    }, children: [_jsx(TextBase.T2, { children: safeToFixed(wrapAmount, 4, true) }), _jsxs(TextBase.T2, { children: ["w", nativeToken.toUpperCase()] })] }) }), _jsx(Row, { style: { margin: "0 0 12px 0" } }), _jsxs(Row, { children: [_jsx(TextBase.F2, { gray: true, children: `To start, you need to turn your ${nativeToken.toUpperCase()} into ERC-20 w${nativeToken.toUpperCase()} token using the most credible solution on the market` }), _jsx(Icons.Radar, {})] })] })] }), _jsx(Button, { size: "xs", width: "100%", pending: pending, onClick: wrap, children: t `Wrap` })] }));
};
const chainHelp = {
    "97": "https://academy.binance.com/en/articles/connecting-metamask-to-binance-smart-chain",
};
const beUrl = {
    default: "https://etherscan.io",
    "4": "https://rinkeby.etherscan.io",
    "56": "https://bscscan.com/",
    "97": "https://testnet.bscscan.com/",
    "128": "https://hecoinfo.com/",
    "137": "https://polygonscan.com/",
    "256": "https://testnet.hecoinfo.com/",
    "80001": "https://mumbai.polygonscan.com/",
};
// TODO config
const chains = {
    "1": {
        chainId: "0x1",
    },
    "4": {
        chainId: "0x4",
    },
    "56": {
        chainId: "0x38",
        chainName: "Binance Smart Chain",
        nativeCurrency: {
            name: "BNB",
            symbol: "BNB",
            decimals: 18,
        },
        rpcUrls: ["https://bsc-dataseed.binance.org/"],
        blockExplorerUrls: ["https://bscscan.com"],
    },
    "97": {
        chainId: "0x61",
        chainName: "Binance Smart Chain - Testnet",
        nativeCurrency: {
            name: "BNB",
            symbol: "BNB",
            decimals: 18,
        },
        rpcUrls: ["https://data-seed-prebsc-1-s1.binance.org:8545/"],
        blockExplorerUrls: ["https://testnet.bscscan.com"],
    },
};
export const DepositERC20 = ({ hasAssets, address, amount, bridgeAddress, tokenAddress, spender, dest, resourceId, wrap, onSuccess, onError, onCopy, setDepositTx, setBridgeBalance, setStep, token, chainName, chainId, }) => {
    const { native, stable } = useAssets();
    const { address: ethAddress, chainId: currentChainId, switchChain, } = useEthereum();
    const blockExplorer = React.useMemo(() => beUrl[parseInt((currentChainId ?? "0x00").slice(2), 16).toString()] ??
        beUrl.default, [currentChainId]);
    const { allowance, balance, symbol, approve, deposit, updateBalance, bridgeBalance, } = useERC20Deposit({
        bridgeAddress,
        tokenAddress,
        spender,
        dest,
        resourceId,
    });
    const [approvePending, setApprovePending] = React.useState(false);
    const [depositPending, setDepositPending] = React.useState(false);
    const [approveTransaction, setApproveTransaction] = React.useState("");
    const isApproved = React.useMemo(() => Number.isFinite(Number(amount)) &&
        Number(amount) > 0 &&
        allowance &&
        allowance.gte(amount), [allowance, amount]);
    const isLowBalance = React.useMemo(() => !balance?.gte(amount ?? 0), [amount, balance]);
    const sendApprove = React.useCallback(async () => {
        if (!balance?.gte(amount ?? 0)) {
            throw new Error("low balance");
        }
        if (amount) {
            setApprovePending(true);
            try {
                const tx = await approve(amount);
                onSuccess?.("approve", tx);
                setApproveTransaction(tx.transactionHash);
            }
            catch (e) {
                if (e instanceof Error) {
                    onError?.("approve", e);
                }
                else {
                    onError?.("approve", new Error("UNKNOWN_ERROR"));
                }
            }
            finally {
                setApprovePending(false);
            }
        }
        else {
            throw new Error("invalid amount");
        }
    }, [amount, balance, approve, onError, onSuccess]);
    const sendDeposit = React.useCallback(async () => {
        if (!allowance?.gte(amount ?? 0)) {
            throw new Error("transfer not approved");
        }
        if (amount) {
            setDepositPending(true);
            try {
                const tx = await deposit(amount, address);
                onSuccess?.("deposit", tx);
                if (!!setDepositTx)
                    setDepositTx(tx);
            }
            catch (e) {
                if (e instanceof Error) {
                    console.warn(e.message);
                    onError?.("deposit", e);
                }
            }
            finally {
                setDepositPending(false);
            }
        }
        else {
            throw new Error("invalid amount");
        }
    }, [address, amount, allowance, deposit, onError, onSuccess]);
    const { ethBalance, deposit: wrapDeposit, balance: wrapBalance, } = useWrappedETH(tokenAddress);
    const wrapAmount = React.useMemo(() => {
        return wrapBalance?.times(-1).plus(amount ?? 0);
    }, [amount, wrapBalance]);
    const isDone = React.useMemo(() => !!wrapAmount?.lte(0), [wrapAmount]);
    React.useEffect(() => {
        if (!!setBridgeBalance && bridgeBalance) {
            setBridgeBalance(bridgeBalance.toFixed(2));
        }
    }, [bridgeBalance]);
    React.useEffect(() => {
        if (!!setStep) {
            if (!amount || (!isDone && wrapAmount?.isFinite() && wrapAmount.gt(0))) {
                setStep("Deposit");
            }
            else {
                setStep("Approve transfers");
            }
            if (isApproved) {
                setStep("Confirm deposit");
            }
            if (!ethAddress) {
                setStep("Connect wallet");
            }
        }
    }, [ethAddress, isDone, wrapAmount, isApproved, amount]);
    const helpLink = React.useMemo(() => chainHelp[chainId ?? ""], [chainId]);
    const nativeToken = React.useMemo(() => (["0x1", "0x4"].includes(currentChainId ?? "") ? "Eth" : "Bnb"), [currentChainId]);
    if (!ethAddress) {
        return _jsx(EthConnect, {});
    }
    return (_jsxs(_Fragment, { children: [token === nativeToken && ethBalance ? (_jsx("div", { style: { position: "relative", zIndex: 10, cursor: "pointer" }, children: _jsx(TextBase.F2, { onClick: () => onCopy &&
                        onCopy(ethBalance
                            .plus(balance ?? 0)
                            .dp(9)
                            .toString()), gray: true, style: { position: "absolute", top: "-28px" }, children: `Available: ${ethBalance
                        .plus(balance ?? 0)
                        .dp(9)
                        .toString()} ${nativeToken.toUpperCase()}` }) })) : symbol && balance ? (_jsx("div", { style: { position: "relative", zIndex: 10, cursor: "pointer" }, children: _jsx(TextBase.F2, { onClick: () => onCopy && onCopy(balance.dp(9).toString()), gray: true, style: { position: "absolute", top: "-28px" }, children: `Available: ${balance
                        .dp(9)
                        .toFixed(2)} ${symbol.toUpperCase()}` }) })) : undefined, parseInt((currentChainId ?? "0x00").slice(2), 16).toString() !==
                chainId && (_jsxs(Box, { className: "label", mt: "16px", children: [_jsx(TextBase.F2, { fontFamily: "Bold", children: t `Warning!` }), _jsx(TextBase.F2, { children: t `Network selected in metamask is not ${chainName ?? "Ethereum"}` }), _jsx(TextBase.F2, { children: _jsx("a", { href: "javascript:void(0);", onClick: () => switchChain(chains[chainId ?? "4"]), children: t `Switch chain` }) })] })), wrap && !isDone && wrapAmount?.isFinite() && wrapAmount.gt(0) ? (_jsx(WrapETH, { nativeToken: nativeToken, ethBalance: ethBalance, deposit: wrapDeposit, wrapAmount: wrapAmount, wrapBalance: wrapBalance, tokenAddress: tokenAddress, updateBalance: updateBalance, onError: onError?.bind(null, "weth"), onSuccess: onSuccess?.bind(null, "weth"), onCopy: onCopy })) : (_jsxs(_Fragment, { children: [_jsxs(Row, { alignItems: "center", noWrap: true, style: { marginTop: 16 }, children: [isApproved ? (_jsx(ButtonWrapper, { className: "signed", children: _jsx(Signed, {}) })) : (_jsx(Button
                            // @ts-ignore
                            , { 
                                // @ts-ignore
                                width: "80px", size: "xs", disabled: !amount || isLowBalance || Number(amount) <= 0, onClick: sendApprove, pending: approvePending, children: t `Approve` })), _jsx(Box, { pl: "16px", children: _jsx(TextBase.F3, { gray: true, children: isApproved ? (_jsxs(_Fragment, { children: [t `Transfers are approved`, _jsx("br", {}), approveTransaction && (_jsxs("a", { href: `${blockExplorer}/tx/${approveTransaction}`, target: "_blank", style: { textDecoration: "none" }, children: [_jsx(TextBase.F3, { as: "span", gray: true, style: { textDecoration: "underline" }, children: `${approveTransaction.slice(0, 6)}...${approveTransaction.slice(-6)}` }), _jsx(Icons.Etherscan, {})] }))] })) : (_jsxs(_Fragment, { children: [t `Approve smart contract`, _jsx("br", {}), t `to spend your tokens`] })) }) })] }), _jsx(Space, { height: 12 }), _jsxs(Row, { alignItems: "center", noWrap: true, children: [_jsx(Button
                            // @ts-ignore
                            , { 
                                // @ts-ignore
                                width: "80px", size: "xs", disabled: !isApproved, onClick: sendDeposit, pending: depositPending, children: t `Deposit` }), _jsx(Box, { pl: "16px", children: _jsx(TextBase.F3, { gray: true, children: t `Transfer selected asset cross-chain to use it inside Equilibrium` }) })] })] })), _jsxs(Accordion, { style: { width: "100%", marginTop: 12 }, children: [!hasAssets && (_jsx(Accordion.Item, { titleStyle: {
                            minHeight: 18,
                        }, title: _jsx(TextBase.F2, { fontFamily: "Bold", gray: true, children: t `First deposit details` }), content: _jsx(FirstDepositDetails, { amount: native === "Gens" ? 100 : 10, asset: native.toUpperCase(), price: "1" }) })), _jsx(Accordion.Item, { titleStyle: {
                            minHeight: 18,
                        }, title: _jsx(TextBase.F2, { fontFamily: "Bold", gray: true, children: t `Chainsafe bridge` }), content: _jsxs("div", { className: "label", children: [_jsxs(Row, { spaceBetween: true, children: [_jsx(TextBase.F2, { children: t `Bridge name` }), _jsx(TextBase.F2, { children: "Chainsafe" })] }), _jsxs(Row, { spaceBetween: true, children: [_jsx(TextBase.F2, { children: t `Website` }), _jsx("a", { href: "https://chainsafe.io/", target: "_blank", rel: "noopener noreferrer", style: { textDecoration: "none" }, children: _jsx(TextBase.F2, { children: "chainsafe.io" }) })] }), _jsxs(Row, { spaceBetween: true, children: [_jsx(TextBase.F2, { children: t `Bridge address` }), _jsxs("a", { href: "https://rinkeby.etherscan.io/address/0xb1b3F694023179e59ff07F7994A631083d01F38f", target: "_blank", rel: "noopener noreferrer", style: {
                                                textDecoration: "none",
                                                display: "flex",
                                                alignItems: "center",
                                            }, children: [_jsx(Icons.Etherscan, {}), _jsx(TextBase.F2, { as: "span", children: "0xb1...F38f" })] })] }), bridgeBalance && bridgeBalance.gt(0) && (_jsxs(Row, { spaceBetween: true, children: [_jsx(TextBase.F2, { children: t `Total value locked` }), _jsxs(TextBase.F2, { children: [bridgeBalance.toString(), " ", token.toUpperCase()] })] }))] }) })] })] }));
};
//# sourceMappingURL=index.js.map