import BigNumber from "bignumber.js";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useApi } from "../../contexts/polkadot/api";
import { useAssets } from "../../contexts/polkadot/assets";
import { useAccounts } from "../../contexts/polkadot/connect";
import { useNetwork } from "../../contexts/polkadot/network";
import { useAccount } from "../../contexts/polkadot/sub-account";
import { Period } from "./types";
const mul = new BigNumber(10, 10).pow(9);
const converter = (a) => a ?? new BigNumber(0);
const totalBalance = (bal, convert = converter) => (bal &&
    Object.entries(bal).reduce((b, [c, a]) => {
        return b.plus(convert(a));
    }, new BigNumber(0))) ??
    new BigNumber(0);
export const isScreen = (raw) => ["settings", "wallet", "deposit", "transfer", "withdraw"].includes(raw);
/** @deprecated was using old contexts; mosts likely to be broken */
export const useSidebar = (convert = converter) => {
    const { availableTokens: tokens } = useAssets();
    const { network, networks, setNetworkIndex } = useNetwork();
    const { api } = useApi();
    const { accounts, select, connected } = useAccounts();
    const balance = {}; // TODO use new api
    const { getAccount } = useAccount();
    const { firstBlockAt, block } = {};
    const [token, setToken] = useState("Eqd");
    const [period, setPeriod] = useState(Period.Day);
    const [hasAssets, setHasAssets] = useState(false);
    useEffect(() => {
        const [token] = tokens ?? [];
        if (token) {
            setToken(token);
        }
    }, [tokens]);
    const [transferExtrinsic, setTransferExtrinsic] = useState();
    /** @deprecated */
    const [withdrawExtrinsic, setWithdrawExtrinsic] = useState();
    const createTransferExtrinsic = useCallback((amount, token, subAccount) => {
        if (api) {
            const value = mul.times(amount);
            if (value.gt(0)) {
                const ex = api.tx.transferTo(subAccount, token, mul.times(amount).toFixed(0));
                // fixme types bug
                setTransferExtrinsic(ex);
            }
            else {
                setTransferExtrinsic(undefined);
            }
        }
        else {
            setTransferExtrinsic(undefined);
        }
    }, [api]);
    /** @deprecated */
    const createWithdrawExtrinsic = useCallback((amount, token, address, crossChain) => {
        if (api) {
            try {
                const value = mul.times(amount);
                if (value.gt(0)) {
                    let ex;
                    if (!crossChain) {
                        ex = api.tx.transfer(
                        //@ts-ignore
                        token, address, value.toFixed(0));
                    }
                    else {
                        ex = api._api.tx.eqBridge.transferNative(value.toFixed(0), address, crossChain.nativeChainId, crossChain.resourceId);
                    }
                    setWithdrawExtrinsic(ex);
                }
                else {
                    setWithdrawExtrinsic(undefined);
                }
            }
            catch (_) {
                setWithdrawExtrinsic(undefined);
            }
        }
        else {
            setWithdrawExtrinsic(undefined);
        }
    }, [api]);
    const [tab, setTab] = useState("wallet");
    useEffect(() => {
        if (!isScreen(tab)) {
            setToken(tab);
        }
    }, [tab]);
    const openSettings = useCallback(() => {
        setTab("settings");
    }, [tab]);
    const close = useCallback(() => setTab("wallet"), []);
    const selectAccount = useCallback((address) => {
        const acc = accounts?.find((acnt) => acnt.address === address);
        if (acc) {
            select(acc);
        }
    }, [accounts, select]);
    const selectNetwork = useCallback((net) => {
        setNetworkIndex(networks.findIndex((n) => n.name == net?.name));
        setTimeout(() => window.location.reload(), 20);
    }, [networks, setNetworkIndex]);
    const suggest = useMemo(() => {
        const master = getAccount();
        if (master) {
            // @ts-expect-error
            if (totalBalance(balance?.[master.address]).lte(0)) {
                return "LowBalance";
            }
        }
        // TODO Bailsman suggest
        return undefined;
    }, [balance, getAccount]);
    useEffect(() => {
        const account = getAccount();
        if (account && balance) {
            const hasAssets = 
            // @ts-expect-error
            Object.entries(balance[account.address] ?? {}).filter(
            // @ts-expect-error
            ([_, amount]) => amount && amount.gt(0)).length > 0;
            setHasAssets(hasAssets);
        }
    }, [balance]);
    /*
  
    const hasAssets =
      balance &&
      Object.entries(balance).filter(([_, amount]) => amount && amount.gt(0)).length > 0;
  
    */
    return {
        getAccount,
        network,
        accounts,
        networks,
        convert,
        balance,
        tab,
        setTab,
        openSettings,
        close,
        selectAccount,
        selectNetwork,
        transferExtrinsic,
        createTransferExtrinsic,
        period,
        setPeriod,
        suggest,
        token,
        setToken,
        connected,
        withdrawExtrinsic,
        createWithdrawExtrinsic,
        hasAssets,
        firstBlockAt,
        block,
    };
};
//# sourceMappingURL=hooks.js.map