'use client'
import { __awaiter } from '../../../../../../_virtual/_tslib.js';
import { useMemo, useCallback } from 'react';
import { DynamicError } from '@dynamic-labs/utils';
import { getDynamicClient } from '../../../../client/client.js';
import '@dynamic-labs/sdk-api-core';
import '@dynamic-labs-sdk/client/core';
import '@dynamic-labs-sdk/client';
import '../../../../config/ApiEndpoint.js';
import '@dynamic-labs/iconic';
import '@dynamic-labs/wallet-connector-core';
import 'react/jsx-runtime';
import '../../../ViewContext/ViewContext.js';
import '../../../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '../../../../utils/constants/colors.js';
import '../../../../utils/constants/values.js';
import '../../../../shared/consts/index.js';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import '../../../../store/state/nonce/nonce.js';
import { getEnvironmentId } from '../../../../store/state/dynamicContextProps/dynamicContextProps.js';
import { getPrimaryWalletId } from '../../../../store/state/primaryWalletId/primaryWalletId.js';
import { useConnectedWalletsInfo, setConnectedWalletsInfo } from '../../../../store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import '../../../../events/dynamicEvents.js';
import '@dynamic-labs/locale';
import { unlinkWallet } from '../../../../data/api/wallets/wallets.js';
import { getAuthMode } from '../../../../store/state/authMode/authMode.js';
import { useInternalUserWallets } from '../../../UserWalletsContext/UserWalletsContext.js';

const useRemoveWallet = ({ secondaryWallets, handleLogOut, setPrimaryWallet, }) => {
    const { removedWalletsIds, userWallets } = useInternalUserWallets();
    const connectedWalletsInfo = useConnectedWalletsInfo();
    const nextWalletId = useMemo(() => (secondaryWallets[0] ? secondaryWallets[0].id : undefined), [secondaryWallets]);
    const callback = useCallback((walletId, clearStackAndPushInitialView) => __awaiter(void 0, void 0, void 0, function* () {
        var _a;
        const wallet = userWallets.find((w) => w.id === walletId);
        if (!wallet)
            return;
        const primaryWalletId = getPrimaryWalletId();
        const isUnlinkingPrimaryWallet = walletId === primaryWalletId;
        const authMode = getAuthMode();
        const user = (_a = getDynamicClient()) === null || _a === void 0 ? void 0 : _a.user;
        if (authMode === 'connect-and-sign') {
            const isLastVerifiedCredential = (user === null || user === void 0 ? void 0 : user.verifiedCredentials.length) === 1;
            if (isLastVerifiedCredential) {
                throw new DynamicError('This is your only login method. Add another wallet or log in method before removing it.');
            }
            yield unlinkWallet({
                environmentId: getEnvironmentId(),
                onSuccess: () => {
                    removedWalletsIds.current.push(walletId);
                },
                // primaryWalletId is the suggestion of the next credential to be set as lastVerifiedCredential
                // If we're unlinking the primary wallet, we don't want to set it to that!
                primaryWalletId: isUnlinkingPrimaryWallet
                    ? undefined
                    : primaryWalletId,
                walletId,
            });
        }
        else {
            removedWalletsIds.current.push(walletId);
        }
        const updatedConnectedWalletsInfo = connectedWalletsInfo.filter((wallet) => wallet.id !== walletId);
        setConnectedWalletsInfo(updatedConnectedWalletsInfo);
        if (isUnlinkingPrimaryWallet && nextWalletId) {
            setPrimaryWallet(nextWalletId);
        }
        // If there are no wallets left and no user (connect-only), we need to log out
        if (!user && !nextWalletId) {
            handleLogOut();
            return;
        }
        const numberOfWalletsWithSameConnector = userWallets.filter(({ connector }) => connector.key === wallet.connector.key).length;
        // If there's only 1, it's the one being removed and we can kill the session
        if (numberOfWalletsWithSameConnector === 1) {
            yield wallet.connector.endSession();
        }
    }), [
        userWallets,
        connectedWalletsInfo,
        nextWalletId,
        removedWalletsIds,
        setPrimaryWallet,
        handleLogOut,
    ]);
    return callback;
};

export { useRemoveWallet };
