import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { createServiceApi, isEthAddress } from "@equilab/utils";
import BigNumber from "bignumber.js";
import React from "react";
import styled from "styled-components";
import { t } from "ttag";
import { EthereumProvider } from "../../contexts/ethereum";
import { PolkadotProvider } from "../../contexts/polkadot";
import { BaseProvider, useBase } from "../../contexts/substrate/base";
import Button from "../button";
import { DepositERC20 } from "../cross-chain/eth";
import { AppContent, Box, Page } from "../grid";
import Sidebar from "./";
import { isScreen } from "./hooks";
import historyMock from "./history.mock";
import { useFetch } from "../../hooks/common";
const meta = {
    title: "Composed/Sidebar",
    component: Sidebar,
};
const Wrapper = styled.div `
  height: 100%;
`;
export default meta;
const config = {
    Eth: [
        {
            hostChainId: "1",
            nativeChainId: "0",
            resourceId: "0x000000000000000000000000000000e7af8cdba234ffeeddccbbaa3458798700",
            metamaskChainId: "4",
            name: "Rinkeby Testnet",
            addressPlaceholder: "0x".padEnd(42, "0"),
            addressValidation: isEthAddress,
            chainSpec: {
                ethBridgeAddress: "0xb1b3F694023179e59ff07F7994A631083d01F38f",
                ethTokenAddress: "0x1715fb41d1b70Db7E14b84a902acd14B34F87c41",
                ethSpenderAddress: "0xCD7cB50593c5191C453D2af0A000bEDD3DA88ED0",
                ethWrap: true,
            },
        },
    ],
    Eq: [
        {
            hostChainId: "1",
            nativeChainId: "0",
            resourceId: "0x000000000000000000000000000000c76ebe4a02bbc34786d860b355f5a5ce00",
            metamaskChainId: "4",
            name: "Rinkeby Testnet",
            addressPlaceholder: "0x".padEnd(42, "0"),
            addressValidation: isEthAddress,
            chainSpec: {
                ethBridgeAddress: "0xb1b3F694023179e59ff07F7994A631083d01F38f",
                ethTokenAddress: "0x485517f213981f036A319A725c045804BbEB91C1",
                ethSpenderAddress: "0xCD7cB50593c5191C453D2af0A000bEDD3DA88ED0",
            },
        },
    ],
};
const Inner = ({ demoDex }) => {
    const { getAccount, accounts, network, networks, openSettings, tab, close, selectAccount, selectNetwork, setTab, convert, balance, transferExtrinsic, createTransferExtrinsic, withdrawExtrinsic, createWithdrawExtrinsic, period, setPeriod, suggest, token, setToken, connected, hasAssets, block, firstBlockAt, } = Sidebar.useSidebar(() => new BigNumber(1));
    const account = React.useMemo(() => getAccount(), [getAccount]);
    const api = React.useMemo(() => createServiceApi({
        endpoint: "https://app.equilibrium.io/testnet/service",
    }), []);
    // Faucet for tokens
    const [pending, setPending] = React.useState(false);
    const deposit = React.useCallback(async (amount, token) => {
        try {
            await api.deposit({
                address: account.address,
                currency: token,
                amount: new BigNumber(amount).times(1000000000).toString(),
            });
            close();
        }
        catch (e) {
            if (e instanceof Error) {
                console.error(e.message);
            }
        }
        finally {
            setPending(false);
        }
    }, [account, api, close]);
    // End of faucet
    const chainDeposit = React.useMemo(() => {
        if (config[token]?.length) {
            const crossChain = config[token][0];
            // TODO switch for token type
            return (props) => (_jsx(Box, { p: "0px 16px 12px 16px", children: _jsx(DepositERC20, { chainId: crossChain.metamaskChainId ?? "1", chainName: crossChain.name, address: account?.address, amount: props.amount, dest: crossChain.hostChainId, resourceId: crossChain.resourceId, spender: crossChain.chainSpec?.ethSpenderAddress, bridgeAddress: crossChain.chainSpec?.ethBridgeAddress, tokenAddress: crossChain.chainSpec?.ethTokenAddress, wrap: crossChain.chainSpec?.ethWrap, onSuccess: console.info, onError: console.warn, onCopy: props.setAmount, token: token }) }));
        }
        return (props) => (_jsx(Box, { p: "12px 16px", children: _jsx(Button, { onClick: () => props.amount && deposit(props.amount, token), width: "100%", size: "sm", dark: true, disabled: !Number(props.amount) || pending, pending: pending, children: t `Deposit` }) }));
    }, [token, deposit, pending, account]);
    const parsePayload = (raw) => JSON.parse(raw);
    const getDefChainPrices = useFetch({
        query: `https://apiv2.equilibrium.io/api/prices`,
        method: "get",
        predicate: (_) => true,
        parsePayload,
    }, false);
    return (_jsx(Wrapper, { children: _jsx(Sidebar, { force: "expanded", isDex: demoDex, children: !account ? (_jsx(Sidebar.GetStarted, { network: network, networks: networks, connected: connected, onNetworkChange: selectNetwork })) : (_jsxs(_Fragment, { children: [_jsx(Sidebar.Header, { account: account, network: network, onClick: openSettings }), (tab === "wallet" || !isScreen(tab)) && (_jsx(Sidebar.Actions, { suggest: suggest, onSwitch: setTab, network: network })), tab === "settings" && (_jsx(Sidebar.Settings, { account: account, accounts: accounts ?? [], network: network, networks: networks, onClose: close, onAccountChange: selectAccount, onNetworkChange: selectNetwork })), tab === "wallet" && (_jsx(Sidebar.Wallet, { onSwitch: setTab, 
                        // @ts-expect-error
                        convert: convert, account: account, 
                        // @ts-expect-error
                        balance: balance?.[account.address] })), tab === "deposit" && (_jsx(Sidebar.Deposit, { token: token, setToken: setToken, onClose: close, network: network, hasAssets: hasAssets, 
                        // @ts-expect-error
                        convert: convert, children: chainDeposit })), tab === "withdraw" && (_jsx(Sidebar.Withdraw, { account: account, token: token, setToken: setToken, 
                        // @ts-expect-error
                        balance: balance?.[account.address], onClose: close, extrinsic: withdrawExtrinsic, onChange: createWithdrawExtrinsic, onError: console.log, config: config })), tab === "transfer" && (_jsx(Sidebar.Transfer, { token: token, setToken: setToken, 
                        // @ts-expect-error
                        balance: balance?.[account.address], account: account, onClose: close, onError: console.log, extrinsic: transferExtrinsic, onChange: createTransferExtrinsic })), !isScreen(tab) && (_jsx(Sidebar.History, { block: block, firstBlockAt: firstBlockAt, bailsman: {
                            ...account,
                            address: "5DnoYz3koaRcMZ9Hj4FmQ2nNRKQfS73yBmEzzM9SsPn9cLtb",
                        }, borrower: {
                            ...account,
                            address: "5EbzvRMFGRkqMHLzYKSqPBwc8Bq8fn3TepPH9zXB9ZVhtHdg",
                        }, period: period, setPeriod: setPeriod, account: account, currency: tab, stableCurrency: "Eqd", onClose: close, getRateHistory: getDefChainPrices.exec, transferHistory: historyMock, onSwitch: setTab, network: network, 
                        // @ts-expect-error
                        convert: convert, 
                        // @ts-expect-error
                        balance: balance?.[account.address] }))] })) }) }));
};
export const Default = () => {
    return (_jsx(_Fragment, { children: _jsx(BaseProvider, { init: true, children: _jsx(EthereumProvider, { children: _jsx(PolkadotProvider, { useBase: useBase, name: "equilibrium", networks: [
                        {
                            type: "Eq",
                            name: "Equilibrium",
                            dev: true,
                            node: "wss://testnet.equilibrium.io",
                        },
                        {
                            type: "Gens",
                            name: "Genshiro",
                            dev: true,
                            node: "wss://testnet.genshiro.io",
                        },
                    ], children: _jsx(Page, { children: _jsxs(AppContent, { children: [_jsx(Inner, {}), _jsx("div", { style: { width: 300, height: 700 } })] }) }) }) }) }) }));
};
export const Dex = () => {
    return (_jsx(_Fragment, { children: _jsx(BaseProvider, { init: true, children: _jsx(EthereumProvider, { children: _jsx(PolkadotProvider, { useBase: useBase, name: "equilibrium", networks: [
                        {
                            type: "Eq",
                            name: "Mainet",
                            dev: true,
                            node: "wss://testnet.equilibrium.io",
                        },
                        {
                            type: "Eq",
                            name: "Testnet",
                            dev: true,
                            node: "wss://testnet.equilibrium.io",
                        },
                    ], children: _jsx(Page, { children: _jsx(AppContent, { children: _jsx(Inner, { demoDex: true }) }) }) }) }) }) }));
};
//# sourceMappingURL=index.stories.js.map