'use client'
import { __awaiter } from '../../../../_virtual/_tslib.js';
import { jsx } from 'react/jsx-runtime';
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { ChainEnum } from '@dynamic-labs/sdk-api-core';
import { DynamicError } from '@dynamic-labs/utils';
import { isSendBalanceWalletConnector } from '@dynamic-labs/wallet-connector-core';
import { ChainIcon } from '../../components/ChainIcon/ChainIcon.js';
import { SendBalancePageLayout } from '../../components/SendBalancePageLayout/SendBalancePageLayout.js';
import { Spinner } from '../../components/Spinner/spinner.js';
import { TransactionStatusLayout } from '../../components/TransactionStatusLayout/TransactionStatusLayout.js';
import '../../context/DynamicContext/DynamicContext.js';
import '../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import '@dynamic-labs/iconic';
import '../../context/ViewContext/ViewContext.js';
import { logger } from '../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '../../utils/constants/colors.js';
import '../../utils/constants/values.js';
import '../../shared/consts/index.js';
import { dynamicEvents } from '../../events/dynamicEvents.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 { getEvmChainName } from '../../utils/functions/networksAndChains/networksAndChains.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 '../../store/state/authMode/authMode.js';
import '../../context/VerificationContext/VerificationContext.js';
import 'react-dom';
import '../../utils/functions/compareChains/compareChains.js';
import '../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 '../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 '../../components/Accordion/components/AccordionItem/AccordionItem.js';
import '../../components/Alert/Alert.js';
import '../../components/ShadowDOM/ShadowDOM.js';
import '../../components/IconButton/IconButton.js';
import '../../components/InlineWidget/InlineWidget.js';
import '../../components/Input/Input.js';
import '../../components/IsBrowser/IsBrowser.js';
import '../../components/MenuList/Dropdown/Dropdown.js';
import '../../components/OverlayCard/OverlayCard.js';
import '../../components/Transition/ZoomTransition/ZoomTransition.js';
import '../../components/Transition/SlideInUpTransition/SlideInUpTransition.js';
import '../../components/Transition/OpacityTransition/OpacityTransition.js';
import '../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.js';
import '../../components/Popper/Popper/Popper.js';
import '../../components/Popper/PopperContext/PopperContext.js';
import 'react-focus-lock';
import 'qrcode';
import { useFetchChain } from '../../widgets/DynamicWidget/hooks/useFetchChain/useFetchChain.js';
import { shortenWalletAddress } from '../../shared/utils/functions/shortenWalletAddress/shortenWalletAddress.js';
import 'formik';
import '../../utils/hooks/useSubdomainCheck/useSubdomainCheck.js';
import '../../context/WalletGroupContext/WalletGroupContext.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 '../../widgets/DynamicWidget/context/DynamicWidgetContext.js';
import '../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.js';
import '../ExchangeWhitelistWarning/ExchangeWhitelistWarning.js';
import '../../context/ErrorContext/hooks/useErrorText/useErrorText.js';
import '../../context/FooterAnimationContext/index.js';
import '../MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.js';
import '../../context/PasskeyContext/PasskeyContext.js';
import '../../context/OnrampContext/OnrampContext.js';
import { setSendBalanceVariable, resetSendBalanceState } from '../../store/state/sendBalances.js';
import '../../store/state/connectorsInitializing/connectorsInitializing.js';
import '../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.js';
import '../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.js';
import { TransactionConfirmationView } from '../TransactionConfirmationView/TransactionConfirmationView.js';
import '../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.js';
import '../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.js';
import '../../../index.js';
import '../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.js';
import { useNetworkDataFromWallet } from '../../utils/hooks/useNetworkDataFromWallet/useNetworkDataFromWallet.js';
import { useTokenBalances } from '../../utils/hooks/useTokenBalances/useTokenBalances.js';
import '../../store/state/multichainBalances.js';
import '../../shared/utils/functions/getInitialUrl/getInitialUrl.js';
import { useInternalDynamicContext } from '../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';

const usingNative = (token) => Boolean(token.isNative);
const getTransactionValue = (transaction, isNativeToken) => {
    if (isNativeToken)
        return transaction.value
            ? transaction.format(transaction.value, { precision: 6 })
            : '0';
    return transaction.nonNativeValue && transaction.formatNonNativeToken
        ? transaction.formatNonNativeToken(transaction.nonNativeValue, transaction.nonNativeDecimal || 18)
        : '0';
};
const getSupportedChainName = (connectedChain) => {
    const supportedChains = {
        EVM: ChainEnum.Evm,
        SOL: ChainEnum.Sol,
        SUI: ChainEnum.Sui,
    };
    return connectedChain && connectedChain in supportedChains
        ? supportedChains[connectedChain]
        : ChainEnum.Evm;
};
const SendBalanceView = ({ initialRecipientAddress = '', initialValue, onClickBack, onClickClose, onError, onSuccess, onDone, displayPoweredByDynamicFooter = false, }) => {
    const [stage, setStage] = useState('form');
    const { primaryWallet, walletUiUtils } = useInternalDynamicContext();
    const { t } = useTranslation();
    const [isNativeToken, setIsNativeToken] = useState(false);
    const [currentToken, setCurrentToken] = useState(undefined);
    const [tokenBalances, setTokenBalances] = useState(undefined);
    const [transactionHash, setTransactionHash] = useState(undefined);
    const { showFiat } = useInternalDynamicContext();
    const walletConnector = primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector;
    const { chain } = useFetchChain(walletConnector);
    // token balances are ordered in the backend - this should just be a passthrough
    const { tokenBalances: orderedTokenBalances, isLoading } = useTokenBalances({
        chainName: getSupportedChainName(walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.connectedChain),
        includeFiat: showFiat,
        includeNativeBalance: true,
    });
    if (!primaryWallet) {
        throw new DynamicError('Primary wallet is not available, send balance cannot be displayed');
    }
    if (walletConnector && !isSendBalanceWalletConnector(walletConnector)) {
        throw new DynamicError('Primary wallet is not eligible for this operation. It must implement ISendBalanceWalletConnector');
    }
    const [transaction, setTransaction] = useState(null);
    useEffect(() => {
        const evmChain = (walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.connectedChain) === 'EVM'
            ? getEvmChainName(Number(chain === null || chain === void 0 ? void 0 : chain.chainId))
            : undefined;
        setSendBalanceVariable('chainName', evmChain || (chain === null || chain === void 0 ? void 0 : chain.name) || (walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.connectedChain));
        return () => {
            resetSendBalanceState();
        };
    }, [chain === null || chain === void 0 ? void 0 : chain.chainId, chain === null || chain === void 0 ? void 0 : chain.name, walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.connectedChain]);
    useEffect(() => {
        if (orderedTokenBalances)
            setTokenBalances(orderedTokenBalances);
    }, [orderedTokenBalances]);
    useEffect(() => {
        if (!walletConnector)
            return;
        // If address is zero or 1 address it's native token, otherwise non-native token
        if (currentToken)
            setIsNativeToken(usingNative(currentToken));
        walletConnector
            .createUiTransaction(primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.address)
            .then((transaction) => {
            if (initialRecipientAddress)
                transaction.to = initialRecipientAddress;
            if (initialValue)
                transaction.value = initialValue;
            if (currentToken && !usingNative(currentToken)) {
                transaction.nonNativeAddress = currentToken === null || currentToken === void 0 ? void 0 : currentToken.address;
                transaction.nonNativeValue = BigInt(0);
                transaction.nonNativeDecimal = currentToken === null || currentToken === void 0 ? void 0 : currentToken.decimals;
            }
            setTransaction(transaction);
        })
            .catch((error) => {
            logger.debug('[SendBalanceView] Error creating transaction', error);
            if (error instanceof DynamicError && error.code === '0') {
                // means user cancelled the request for sync'ing the wallet
                onDone === null || onDone === void 0 ? void 0 : onDone();
                return;
            }
            onError === null || onError === void 0 ? void 0 : onError(error);
        });
    }, [currentToken]);
    const networkData = useNetworkDataFromWallet(primaryWallet);
    if (!transaction || !networkData) {
        return (jsx("div", { className: 'send-balance-widget-view__spinner', "data-testid": 'send-balance-spinner', children: jsx(Spinner, {}) }));
    }
    const handleSuccessToRefreshBalance = (txHash) => __awaiter(void 0, void 0, void 0, function* () {
        // SOL
        if ((walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.connectedChain) === 'SOL') {
            // Just to make absolutely sure the block has been validated
            // and confirmed on the Solana blockchain
            setTimeout(() => dynamicEvents.emit('tokenBalancesChanged'), 5000);
        }
        // EVM
        if (walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.confirmTransactionStatus) {
            yield (walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.confirmTransactionStatus(txHash));
            dynamicEvents.emit('tokenBalancesChanged');
        }
    });
    const networkCurrency = (currentToken === null || currentToken === void 0 ? void 0 : currentToken.symbol) || networkData.nativeCurrency.symbol;
    const currencyIcon = (chain === null || chain === void 0 ? void 0 : chain.name) && (jsx(ChainIcon, { chain: chain, chainName: chain.name }));
    const buildFormStage = () => (jsx(SendBalancePageLayout, { transaction: transaction, onClickBack: onClickBack, networkName: networkData.vanityName || networkData.name, networkIcon: currencyIcon, networkCurrencyDecimals: networkData.nativeCurrency.symbol === 'SOL'
            ? 9
            : networkData.nativeCurrency.decimals, walletAddress: shortenWalletAddress(currentToken === null || currentToken === void 0 ? void 0 : currentToken.address), walletKey: primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector.key, onClickClose: onClickClose, displayPoweredByDynamicFooter: displayPoweredByDynamicFooter, onSubmit: () => setStage('confirmation'), tokenBalances: tokenBalances !== null && tokenBalances !== void 0 ? tokenBalances : (currentToken && [currentToken]), currentToken: currentToken, setCurrentToken: setCurrentToken, isLoading: isLoading, isNativeToken: isNativeToken }));
    const buildTransactionStage = () => (jsx(TransactionConfirmationView, { walletConnector: primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector, transaction: transaction, mutation: () => {
            walletUiUtils.disabledConfirmationOnce();
            return transaction.submit();
        }, copykey: 'dyn_send_transaction.confirmation.title', title: t('dyn_send_transaction.confirmation.title'), onClickBack: () => setStage('form'), onError: onError, displayPoweredByDynamicFooter: displayPoweredByDynamicFooter, onSuccess: (txHash) => __awaiter(void 0, void 0, void 0, function* () {
            if (!txHash)
                return;
            onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess(txHash);
            setTransactionHash(txHash);
            setStage('success');
            handleSuccessToRefreshBalance(txHash);
        }), currentToken: currentToken, isNativeToken: isNativeToken, transactionValue: getTransactionValue(transaction, isNativeToken), sendBalanceTransaction: true }));
    const buildSuccessState = () => {
        var _a;
        return (jsx(TransactionStatusLayout, { transactionValue: getTransactionValue(transaction, isNativeToken), destinationAddress: (_a = transaction.to) !== null && _a !== void 0 ? _a : '', networkCurrency: networkCurrency, networkName: networkData.name || '', NetworkIcon: currencyIcon, onClickClose: onClickClose, onDone: () => onDone === null || onDone === void 0 ? void 0 : onDone(), displayPoweredByDynamicFooter: displayPoweredByDynamicFooter, transaction: transaction, currentToken: currentToken, isNativeToken: isNativeToken, transactionHash: transactionHash }));
    };
    const getCurrentView = () => {
        switch (stage) {
            case 'form':
                return buildFormStage();
            case 'confirmation':
                return buildTransactionStage();
            case 'success':
                return buildSuccessState();
        }
    };
    return getCurrentView();
};

export { SendBalanceView, getTransactionValue, usingNative };
