'use client'
import { __awaiter } from '../../../../../../_virtual/_tslib.js';
import { jsx, jsxs } from 'react/jsx-runtime';
import { useState, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { classNames } from '../../../../utils/functions/classNames/classNames.js';
import '../../../Accordion/components/AccordionItem/AccordionItem.js';
import { ReactComponent as SvgStroke } from '../../../../shared/assets/stroke.js';
import '@dynamic-labs/iconic';
import '../../../../context/ViewContext/ViewContext.js';
import '@dynamic-labs/wallet-connector-core';
import '../../../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '@dynamic-labs/utils';
import '../../../../utils/constants/colors.js';
import '../../../../utils/constants/values.js';
import '@dynamic-labs/sdk-api-core';
import '../../../../shared/consts/index.js';
import '../../../Alert/Alert.js';
import '../../../../events/dynamicEvents.js';
import '../../../../context/DynamicContext/DynamicContext.js';
import '../../../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import '../../../../store/state/authMode/authMode.js';
import { useInternalDynamicContext } from '../../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';
import '../../../../context/CaptchaContext/CaptchaContext.js';
import '../../../../context/ErrorContext/ErrorContext.js';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import '../../../../store/state/nonce/nonce.js';
import '@dynamic-labs-sdk/client/core';
import '../../../../client/client.js';
import '@dynamic-labs-sdk/client';
import '../../../../config/ApiEndpoint.js';
import '@dynamic-labs/locale';
import '../../../../store/state/dynamicContextProps/dynamicContextProps.js';
import '../../../../store/state/primaryWalletId/primaryWalletId.js';
import '../../../../store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import '../../../../context/AccessDeniedContext/AccessDeniedContext.js';
import '../../../../context/AccountExistsContext/AccountExistsContext.js';
import '../../../../context/UserWalletsContext/UserWalletsContext.js';
import '../../../../context/VerificationContext/VerificationContext.js';
import 'react-dom';
import '../../../../utils/functions/compareChains/compareChains.js';
import '../../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.js';
import '../../../../context/ThemeContext/ThemeContext.js';
import '../../../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.js';
import 'bs58';
import '@dynamic-labs/types';
import '../../../../context/SocialRedirectContext/SocialRedirectContext.js';
import '../../../../context/LoadingContext/LoadingContext.js';
import '../../../../context/WalletContext/WalletContext.js';
import '../../../../utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.js';
import 'yup';
import '../../../../context/MockContext/MockContext.js';
import '../../../../views/CollectUserDataView/useFields.js';
import '../../../../context/FieldsStateContext/FieldsStateContext.js';
import '../../../../context/UserFieldEditorContext/UserFieldEditorContext.js';
import '@dynamic-labs/rpc-providers';
import '../../../../store/state/walletOptions/walletOptions.js';
import { Typography } from '../../../Typography/Typography.js';
import '../../../../context/FooterAnimationContext/index.js';
import '../../../ShadowDOM/ShadowDOM.js';
import '../../../Transition/ZoomTransition/ZoomTransition.js';
import '../../../Transition/SlideInUpTransition/SlideInUpTransition.js';
import '../../../Transition/OpacityTransition/OpacityTransition.js';
import '../../../OverlayCardBase/OverlayCardTarget/OverlayCardTarget.js';
import { Skeleton } from '../../../Skeleton/Skeleton.js';
import '../../../../context/WalletGroupContext/WalletGroupContext.js';
import '../../../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.js';
import 'react-focus-lock';
import { Icon } from '../../../Icon/Icon.js';
import '../../../../widgets/DynamicWidget/context/DynamicWidgetContext.js';
import '../../../IconButton/IconButton.js';
import '../../../MenuList/Dropdown/Dropdown.js';
import 'formik';
import '../../../../utils/hooks/useSubdomainCheck/useSubdomainCheck.js';
import { setSendBalanceVariable } from '../../../../store/state/sendBalances.js';
import '../../../Input/Input.js';
import { erc20Abi } from '../../../../utils/constants/erc20/abi.js';
import { MenuList } from '../../../MenuList/MenuList/MenuList.js';
import '../../../../views/TransactionConfirmationView/TransactionConfirmationView.js';
import '../../../PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.js';
import '../../../../context/PasskeyContext/PasskeyContext.js';
import '../../../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.js';
import '../../../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.js';
import '../../../../context/OnrampContext/OnrampContext.js';
import '../../../../../index.js';
import '../../../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.js';
import 'qrcode';
import '../../../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.js';
import '../../../../context/IpConfigurationContext/IpConfigurationContext.js';
import '../../../../context/ConnectWithOtpContext/ConnectWithOtpContext.js';
import '../../../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.js';
import '@hcaptcha/react-hcaptcha';
import '../../../../views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.js';
import '../../../../context/ErrorContext/hooks/useErrorText/useErrorText.js';
import '../../../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.js';
import '../../../../store/state/connectorsInitializing/connectorsInitializing.js';
import '../../../../store/state/tokenBalances.js';
import '../../../../store/state/multichainBalances.js';
import '../../../../shared/utils/functions/getInitialUrl/getInitialUrl.js';
import '../../../InlineWidget/InlineWidget.js';
import '../../../IsBrowser/IsBrowser.js';
import '../../../OverlayCard/OverlayCard.js';
import '../../../Popper/Popper/Popper.js';
import '../../../Popper/PopperContext/PopperContext.js';

const TokensBalanceDropdown = ({ tokenBalances, currentToken, setCurrentToken, isLoading, setFieldValue, setErrors, }) => {
    const { t } = useTranslation();
    const [isDropdownOpen, setIsDropdownOpen] = useState(false);
    const filteredTokenBalances = (tokenBalances === null || tokenBalances === void 0 ? void 0 : tokenBalances.filter((token) => token.name)) || [];
    const { primaryWallet } = useInternalDynamicContext();
    const anchorRef = useRef(null);
    const fetchTokenData = (selectedToken) => __awaiter(void 0, void 0, void 0, function* () {
        if (!primaryWallet ||
            !('getPublicClient' in primaryWallet) ||
            typeof primaryWallet.getPublicClient !== 'function') {
            return;
        }
        const publicClient = yield primaryWallet.getPublicClient();
        if (!publicClient)
            return;
        const erc20Contract = {
            abi: erc20Abi,
            address: selectedToken.address,
        };
        const results = yield publicClient.multicall({
            contracts: [
                Object.assign(Object.assign({}, erc20Contract), { args: [primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.address], functionName: 'balanceOf' }),
                Object.assign(Object.assign({}, erc20Contract), { functionName: 'decimals' }),
            ],
        });
        const [balance, decimals] = results.map((v) => Number(v.result));
        if (balance && decimals) {
            selectedToken.balance = balance / Math.pow(10, decimals);
            selectedToken.rawBalance = balance;
            if (tokenBalances) {
                const index = tokenBalances.findIndex((t) => t.name === selectedToken.name);
                tokenBalances[index] = selectedToken;
            }
            selectedToken.decimals = decimals;
        }
    });
    const handleTokenClick = (selectedTokenName) => __awaiter(void 0, void 0, void 0, function* () {
        var _a, _b;
        const selectedToken = (_a = tokenBalances === null || tokenBalances === void 0 ? void 0 : tokenBalances.find((t) => t.name === selectedTokenName)) !== null && _a !== void 0 ? _a : undefined;
        // we dont need to refetch solana balances because we simulate before sending
        if ((selectedToken === null || selectedToken === void 0 ? void 0 : selectedToken.address) && (selectedToken === null || selectedToken === void 0 ? void 0 : selectedToken.address.startsWith('0x'))) {
            fetchTokenData(selectedToken);
        }
        if (selectedToken) {
            if (tokenBalances && ((_b = tokenBalances[0]) === null || _b === void 0 ? void 0 : _b.price))
                setSendBalanceVariable('nativePrice', tokenBalances[0].price);
            setCurrentToken(selectedToken);
            setFieldValue('amount', '');
            setSendBalanceVariable('amount', 0);
            setErrors({});
        }
        setIsDropdownOpen(!isDropdownOpen);
    });
    if (isLoading) {
        return jsx(Skeleton, {});
    }
    const tokenLogo = (token, size) => (token === null || token === void 0 ? void 0 : token.logoURI) ? (jsx("img", { src: token.logoURI, alt: token === null || token === void 0 ? void 0 : token.name, width: size, height: size })) : (jsx("div", { className: 'token-balance-item__skeleton-icon', "data-testid": 'token-balance-item__skeleton-icon' }));
    return (jsxs("div", { className: 'tokens-balance-dropdown', ref: anchorRef, onClick: () => setIsDropdownOpen(!isDropdownOpen), "data-testid": 'tokens-balance-dropdown', children: [!isLoading && (jsxs("div", { className: 'tokens-balance-dropdown__selected', children: [tokenLogo(currentToken, '20'), jsx(Typography, { variant: 'body_normal', color: 'primary', children: currentToken === null || currentToken === void 0 ? void 0 : currentToken.name }), jsx(Icon, { color: 'text-primary', size: 'small', className: classNames('evm-network-control__arrow-icon', {
                            'evm-network-control__arrow-icon--active': isDropdownOpen,
                        }), children: jsx(SvgStroke, {}) })] })), jsx(MenuList, { className: 'tokens-balance-dropdown__menu_list', isOpen: isDropdownOpen, popperProps: {
                    anchorOrigin: 'bottom-left',
                    anchorRef,
                }, mobileTitle: 'Select token', children: filteredTokenBalances.length > 0 ? (filteredTokenBalances.map((t) => (jsxs("button", { className: 'tokens-balance-dropdown__menu_list_item', onClick: () => handleTokenClick(t.name), children: [jsxs("div", { className: 'tokens-balance-dropdown__menu_list_item__name', children: [tokenLogo(t, '16'), jsx(Typography, { variant: 'body_small', color: 'primary', children: t.name })] }), jsxs("div", { className: 'tokens-balance-dropdown__menu_list_item__balance', style: {
                                alignItems: 'flex-end',
                                display: 'flex',
                                flexDirection: 'column',
                            }, children: [jsx(Typography, { variant: 'body_small', color: 'secondary', children: t.symbol }), jsx(Typography, { variant: 'body_small', color: 'primary', children: t.balance })] })] }, t.address)))) : (jsx("div", { className: 'token-balance-list__empty', children: jsx(Typography, { variant: 'body_small', color: 'secondary', copykey: 'dyn_wallet_information.multi_asset.empty_state', children: t('dyn_wallet_information.multi_asset.empty_state') }) })) })] }));
};

export { TokensBalanceDropdown };
