import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { transformBalance } from "@equilab/utils";
import BigNumber from "bignumber.js";
import React, { useCallback, useEffect, useMemo } from "react";
import { t } from "ttag";
import Button from "../button";
import { Box } from "../grid";
import Input from "../input";
import Select from "../select";
import TextBase from "../text";
import { useAssets } from "../../contexts/polkadot/assets";
import BackBtn from "./back";
import { trimNumber } from "../../utils/format";
import { useTheme } from "styled-components";
const BORROW_CURRENCIES_BLACK_LIST = ["Gens"];
const Transfer = ({ account, balance, onClose, onChange, onError, onSuccess, extrinsic, token, setToken, }) => {
    const { currencies, native } = useAssets();
    const [amount, setAmount] = React.useState();
    const [fee, setFee] = React.useState();
    const [pending, setPending] = React.useState(false);
    const [subAccount, setSubAccount] = React.useState("Borrower");
    const tokenBalance = React.useMemo(() => balance?.[token], [balance, token]);
    const theme = useTheme();
    const transferAll = React.useCallback((e) => {
        e.preventDefault();
        if (tokenBalance) {
            setAmount(tokenBalance.toString());
        }
    }, [tokenBalance]);
    const onSubAccountChange = React.useCallback((key) => {
        if (key === "Borrower" || key === "Bailsman") {
            setSubAccount(key);
        }
    }, []);
    const onSubmit = React.useCallback(async () => {
        if (extrinsic) {
            setPending(true);
            try {
                const unsub = await extrinsic.signAndSend(account.address, { nonce: -1 }, (result) => {
                    try {
                        if (result.status.isInBlock || result.status.isFinalized) {
                            setPending(false);
                            unsub();
                            for (const { event: { data, section, method }, } of result.events) {
                                if (section === "system" && method === "ExtrinsicSuccess") {
                                    onSuccess?.();
                                    onClose?.();
                                }
                                if (section === "system" && method === "ExtrinsicFailed") {
                                    const [error] = data;
                                    // @ts-ignore
                                    if (error.isModule) {
                                        onError?.(error.asModule);
                                    }
                                    else {
                                        onError?.(error?.toString());
                                    }
                                }
                            }
                        }
                    }
                    catch (err1) {
                        if (err1 instanceof Error) {
                            console.error(err1?.message);
                        }
                    }
                });
            }
            catch (err2) {
                if (err2 instanceof Error) {
                    onError?.(err2.message);
                }
                setPending(false);
            }
        }
    }, [account, extrinsic, onError, onSuccess, onClose]);
    React.useEffect(() => {
        if (amount) {
            onChange?.(amount, token, subAccount);
        }
    }, [onChange, amount, token, subAccount]);
    React.useEffect(() => {
        (async () => {
            if (extrinsic) {
                const info = await extrinsic.paymentInfo(account.address, {
                    nonce: -1,
                });
                setFee(transformBalance(info.partialFee));
            }
        })();
    }, [account, extrinsic]);
    const handleCurrencySelect = useCallback((cur) => {
        setToken(cur);
    }, [setToken]);
    const tokenInBorrowBlackList = useMemo(() => {
        return BORROW_CURRENCIES_BLACK_LIST.includes(token);
    }, [token]);
    useEffect(() => {
        if (tokenInBorrowBlackList) {
            onSubAccountChange("Bailsman");
        }
    }, [onSubAccountChange, tokenInBorrowBlackList]);
    return (_jsxs(_Fragment, { children: [_jsx(BackBtn, { onClose: onClose }), _jsx(Box, { className: "transfer-label", p: "12px 16px 0", children: _jsx(TextBase.T4, { fontFamily: "Bold", children: t `Transfer assets inside Equilibrium DeFI parachain` }) }), _jsxs("div", { className: "input-token-row", children: [_jsx(Input, { title: t `Amount to transfer`, placeholder: "0", value: amount ?? "", onChange: (val) => {
                            setAmount(trimNumber(val));
                        }, disabled: pending, width: "156px", subscript: tokenBalance?.gt(0) && (_jsxs(TextBase.F2, { style: { position: "relative", top: 14 }, children: [t `Balance`, ":\u00A0", _jsx("a", { onClick: transferAll, href: "#", children: tokenBalance?.toFixed(4, 1) })] })), amount: true, theme: theme?.input }), _jsx(Select, { onSelect: handleCurrencySelect, preselectedKey: token, width: "96px", disabled: pending, theme: theme?.select, children: currencies?.map((token) => (_jsx(Select.Option, { children: token.toUpperCase() }, token))) })] }), _jsx("div", { className: "row transfer-destination", style: {
                    position: "relative",
                    zIndex: 1,
                }, children: _jsxs(Select, { onSelect: onSubAccountChange, title: t `Destination`, width: "100%", preselectedKey: subAccount, theme: theme?.select, children: [!tokenInBorrowBlackList && (_jsx(Select.Option, { children: t `Collateral pool` }, "Borrower")), _jsx(Select.Option, { children: t `Bailout pool` }, "Bailsman")] }) }), _jsxs(Box, { className: "transfer-submit", p: "12px 16px", children: [_jsx(Button, { pending: pending, width: "100%", size: "sm", dark: true, onClick: onSubmit, disabled: !extrinsic ||
                            !tokenBalance ||
                            !amount ||
                            new BigNumber(amount).lte(0) ||
                            tokenBalance.lt(amount) ||
                            pending, children: t `Transfer` }), fee && (_jsxs(Box, { mt: "10px", children: [_jsxs(TextBase.F2, { className: "title", children: [t `Estimated transaction fee`, ":"] }), _jsxs(TextBase.F1, { children: [fee.toFixed(3), " ", native.toUpperCase()] })] }))] })] }));
};
export default Transfer;
//# sourceMappingURL=transfer.js.map