'use client'
import { useCallback, useMemo } from 'react';
import { DynamicError } from '@dynamic-labs/utils';
import { isHardwareWalletConnector } from '@dynamic-labs/wallet-connector-core';
import '../../../context/DynamicContext/useDynamicContext/useDynamicContext.js';
import { useInternalDynamicContext } from '../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';
import { useViewContext } from '../../../context/ViewContext/ViewContext.js';
import { useWalletGroupContext } from '../../../context/WalletGroupContext/WalletGroupContext.js';
import { dynamicEvents } from '../../../events/dynamicEvents.js';
import '@dynamic-labs/iconic';
import 'react/jsx-runtime';
import { logger } from '../../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '../../constants/colors.js';
import '../../constants/values.js';
import { isWalletGroup } from '../../functions/walletListBuilder/utils/isWalletGroup/isWalletGroup.js';
import '@dynamic-labs/sdk-api-core';
import '../../../shared/consts/index.js';
import { useWalletGroups } from '../../../store/state/walletOptions/walletOptions.js';
import { groupWalletOptions } from '../../functions/walletListBuilder/utils/groupWalletOptions/groupWalletOptions.js';
import { useWalletItemActions } from '../useWalletItemActions/useWalletItemActions.js';

const embeddedWalletsKeys = [
    'magicemailotp',
    'magiclink',
    'magicsocial',
    'turnkey',
    'turnkeyhd',
    'zerodev',
    'dynamicwaas',
];
const useWalletOptions = () => {
    const { walletConnectorOptions, setShowAuthFlow } = useInternalDynamicContext();
    const walletGroups = useWalletGroups();
    const { pushView } = useViewContext();
    const { navigateToWalletGroup } = useWalletGroupContext();
    const { handleWalletItemClick } = useWalletItemActions();
    const getFilteredWalletOptions = useCallback((filter) => {
        const nonEmbeddedOptions = walletConnectorOptions.filter((option) => !embeddedWalletsKeys.includes(option.walletConnector.key));
        return filter(nonEmbeddedOptions).map((option) => {
            var _a, _b;
            const groupName = option.group && ((_a = walletGroups[option.group]) === null || _a === void 0 ? void 0 : _a.name);
            return {
                chain: option.walletConnector.connectedChain,
                group: (_b = option.group) !== null && _b !== void 0 ? _b : null,
                groupName: groupName !== null && groupName !== void 0 ? groupName : null,
                isInstalledOnBrowser: option.isInstalledOnBrowser,
                isWalletConnect: option.walletConnector.isWalletConnect,
                key: option.walletConnector.key,
                metadata: option.walletConnector.metadata,
                name: option.name,
                supportedChains: option.walletConnector.supportedChains,
            };
        });
    }, [walletConnectorOptions, walletGroups]);
    const allWalletOptions = useMemo(() => getFilteredWalletOptions((options) => options), [getFilteredWalletOptions]);
    const addListenersToHandleWalletSelectionPromise = useCallback(({ walletKey, connectorName, resolve, reject, }) => {
        const walletAdded = (wallet) => {
            if (wallet.key !== walletKey) {
                return;
            }
            resolve(wallet);
            setShowAuthFlow(false);
            cleanup();
        };
        const walletConnectionFailed = (walletConnector, error) => {
            if (walletConnector.key !== walletKey) {
                return;
            }
            reject(error);
            setShowAuthFlow(false);
            cleanup();
        };
        const authFailure = (method, reason) => {
            if (method.type !== 'wallet' ||
                method.connectorName !== connectorName) {
                return;
            }
            const error = typeof reason === 'object' ? reason.error : reason;
            reject(error);
            setShowAuthFlow(false);
            cleanup();
        };
        const cleanup = () => {
            dynamicEvents.off('walletConnectionFailed', walletConnectionFailed);
            dynamicEvents.off('authFailure', authFailure);
            dynamicEvents.off('walletAdded', walletAdded);
        };
        dynamicEvents.on('walletAdded', walletAdded);
        dynamicEvents.on('walletConnectionFailed', walletConnectionFailed);
        dynamicEvents.on('authFailure', authFailure);
    }, [setShowAuthFlow]);
    const selectWalletOption = useCallback((walletKey, selectGroupIfAvailable = true, skipAllSelectionUi = false, chain) => new Promise((resolve, reject) => {
        const group = groupWalletOptions(walletGroups, walletConnectorOptions);
        const walletGroup = group.find((wallet) => wallet.key === walletKey);
        // Filter by chain if provided
        const walletOption = walletConnectorOptions === null || walletConnectorOptions === void 0 ? void 0 : walletConnectorOptions.find((wallet) => wallet.key === walletKey &&
            (!chain || wallet.walletConnector.connectedChain === chain));
        logger.logVerboseTroubleshootingMessage('[useWalletOptions] selectWalletOption', {
            chain,
            selectGroupIfAvailable,
            walletGroup: walletGroup === null || walletGroup === void 0 ? void 0 : walletGroup.key,
            walletKey,
            walletOption: walletOption === null || walletOption === void 0 ? void 0 : walletOption.key,
        });
        if (!walletOption) {
            const errorMessage = chain
                ? `No wallet found with key "${walletKey}" for chain "${chain}".`
                : `No wallet found with key "${walletKey}".`;
            reject(new DynamicError(errorMessage, 'wallet_not_found'));
            return;
        }
        addListenersToHandleWalletSelectionPromise({
            connectorName: walletOption.walletConnector.name,
            reject,
            resolve,
            walletKey,
        });
        if (skipAllSelectionUi) {
            handleWalletItemClick(walletOption);
            return;
        }
        if (selectGroupIfAvailable &&
            walletGroup &&
            isWalletGroup(walletGroup)) {
            navigateToWalletGroup(walletGroup);
        }
        else if (isHardwareWalletConnector(walletOption.walletConnector) &&
            walletOption.walletConnector.canConnectWithHardwareWallet()) {
            pushView('select-hardware-wallet', {
                onSelectWallet: handleWalletItemClick,
                wallet: walletOption,
            });
        }
        else {
            handleWalletItemClick(walletOption);
        }
        setShowAuthFlow(true);
    }), [
        addListenersToHandleWalletSelectionPromise,
        handleWalletItemClick,
        navigateToWalletGroup,
        setShowAuthFlow,
        pushView,
        walletConnectorOptions,
        walletGroups,
    ]);
    return {
        getFilteredWalletOptions,
        selectWalletOption,
        walletOptions: allWalletOptions,
    };
};

export { useWalletOptions };
