'use client'
import { __awaiter } from '../../../../../_virtual/_tslib.js';
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { useState, useMemo, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { DynamicError, StorageService } from '@dynamic-labs/utils';
import { Checkbox } from '../../../components/Checkbox/Checkbox.js';
import { ErrorContainer } from '../../../components/ErrorContainer/ErrorContainer.js';
import { IconButton } from '../../../components/IconButton/IconButton.js';
import { ModalHeader } from '../../../components/ModalHeader/ModalHeader.js';
import { Typography } from '../../../components/Typography/Typography.js';
import { TypographyButton } from '../../../components/TypographyButton/TypographyButton.js';
import { useDynamicContext } from '../../../context/DynamicContext/useDynamicContext/useDynamicContext.js';
import { useInternalDynamicContext } from '../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';
import { dynamicEvents } from '../../../events/dynamicEvents.js';
import { getProperErrorMessage } from '../../../modals/SignMessageConfirmationModal/getProperErrorMessage.js';
import { ReactComponent as SvgArrowLeft } from '../../../shared/assets/arrow-left.js';
import { ReactComponent as SvgCheck } from '../../../shared/assets/check.js';
import { ReactComponent as SvgClose } from '../../../shared/assets/close.js';
import { ReactComponent as SvgQuestionMark } from '../../../shared/assets/question-mark.js';
import { ReactComponent as SvgQuestion } from '../../../shared/assets/question.js';
import { ReactComponent as SvgSwitchHorizontal } from '../../../shared/assets/switch-horizontal.js';
import '@dynamic-labs/iconic';
import '../../../context/ViewContext/ViewContext.js';
import { logger } from '../../../shared/logger.js';
import { useMutation } from '../../../utils/hooks/useMutation/useMutation.js';
import { useAppName } from '../../../store/utils/settingsUtils/settingsUtils.js';
import { WalletIconWithNetwork } from '../../../widgets/DynamicWidget/components/WalletIconWithNetwork/WalletIconWithNetwork.js';
import { useWalletDelegation } from '../../../utils/hooks/useWalletDelegation/useWalletDelegation.js';
import { DELEGATION_STATE } from '../../../utils/constants/localStorage.js';
import '../../../utils/constants/colors.js';
import '../../../utils/constants/values.js';
import { AgreementSection } from './AgreementSection.js';

const WalletDelegationView = ({ wallets, }) => {
    const { setShowAuthFlow, handleLogOut } = useInternalDynamicContext();
    const { user } = useDynamicContext();
    const appName = useAppName();
    const { getWalletsToDelegate, delegateKeyShares } = useWalletDelegation();
    const { requiresDelegation, denyWalletDelegation, getWalletsDelegatedStatus, } = useWalletDelegation();
    const [selectedWallets, setSelectedWallets] = useState(new Set());
    const [showEditView, setShowEditView] = useState(false);
    const [showLearnMoreView, setShowLearnMoreView] = useState(false);
    const [agreementChecked, setAgreementChecked] = useState(false);
    const [selectionInitialized, setSelectionInitialized] = useState(false);
    // Get waas wallets that are not yet delegated or use provided wallets override
    const waasWallets = useMemo(() => getWalletsToDelegate(wallets, getWalletsDelegatedStatus), [wallets, getWalletsDelegatedStatus]);
    // Auto-select wallets only on initial load
    useEffect(() => {
        if (selectionInitialized)
            return;
        if (waasWallets.length === 1) {
            setSelectedWallets(new Set([waasWallets[0].id]));
            setSelectionInitialized(true);
        }
        else if (waasWallets.length > 1) {
            setSelectedWallets(new Set(waasWallets.map((w) => w.id)));
            setSelectionInitialized(true);
        }
    }, [waasWallets, selectionInitialized]);
    const handleWalletToggle = (walletId, event) => {
        // Prevent event propagation if called from checkbox
        if (event) {
            event.stopPropagation();
        }
        setSelectionInitialized(true);
        setSelectedWallets((prev) => {
            const newSet = new Set(prev);
            if (newSet.has(walletId)) {
                newSet.delete(walletId);
            }
            else {
                newSet.add(walletId);
            }
            return newSet;
        });
    };
    const handleSelectAll = () => {
        setSelectionInitialized(true);
        setSelectedWallets(new Set(waasWallets.map((wallet) => wallet.id)));
    };
    const handleDeselectAll = () => {
        setSelectionInitialized(true);
        setSelectedWallets(new Set());
    };
    const handleDenySelectedWallets = () => __awaiter(void 0, void 0, void 0, function* () {
        try {
            // Deny each selected wallet
            for (const walletId of selectedWallets) {
                yield denyWalletDelegation(walletId);
            }
            // Close the auth flow after successful denial
            setShowAuthFlow(false);
        }
        catch (error) {
            logger.error('Failed to deny wallet delegation', error);
            // Still close the flow even on error to avoid blocking the user
            setShowAuthFlow(false);
        }
    });
    const { mutate: handleDelegateWallets, isLoading, error, data: isSuccess, } = useMutation(() => __awaiter(void 0, void 0, void 0, function* () {
        if (selectedWallets.size === 0) {
            throw new DynamicError('No wallets selected for delegation');
        }
        const selectedWalletObjects = waasWallets.filter((wallet) => selectedWallets.has(wallet.id));
        // Prepare delegation array
        const walletsToDelegate = selectedWalletObjects.map((wallet) => ({
            accountAddress: wallet.address,
            chainName: wallet.chain,
        }));
        try {
            // Delegate all wallets at once
            yield delegateKeyShares(walletsToDelegate);
            // Emit success event for each wallet
            selectedWalletObjects.forEach((wallet) => {
                dynamicEvents.emit('embeddedWalletDelegationCompleted', wallet);
            });
        }
        catch (error) {
            logger.error('Failed to delegate wallets', error);
            throw error;
        }
        // Delegation completion is tracked by the backend through keyShares
        // No need to update local storage
        // Emit overall success event
        dynamicEvents.emit('embeddedWalletDelegationCompleted', selectedWalletObjects[0]);
        return true;
    }), {
        onFailure: (err) => {
            logger.error('Failed to delegate wallets', err);
            dynamicEvents.emit('embeddedWalletDelegationFailed', err);
        },
    });
    const errorText = useMemo(() => {
        if (!error) {
            return undefined;
        }
        if (error instanceof DynamicError) {
            return error.message;
        }
        try {
            return getProperErrorMessage(error, user);
        }
        catch (e) {
            logger.error('Error getting proper error message', e);
            return;
        }
    }, [error, user]);
    const { t } = useTranslation();
    const getSelectButtonText = () => {
        if (selectedWallets.size === waasWallets.length) {
            return t('dyn_wallet_delegation.deselect_all');
        }
        if (selectedWallets.size === 0) {
            return t('dyn_wallet_delegation.select_all');
        }
        return t('dyn_wallet_delegation.clear');
    };
    // Loading state content
    const loadingContent = (jsx("div", { className: 'embedded-delegated-view__body__description', children: jsxs("div", { className: 'embedded-delegated-view__approval-section', children: [jsx("div", { className: 'embedded-delegated-view__approval-icon', children: jsx(SvgSwitchHorizontal, {}) }), jsx(Typography, { variant: 'body_small', weight: 'bold', color: 'primary', className: 'embedded-delegated-view__approval-title', children: t('dyn_wallet_delegation.approving_permissions', { appName }) }), jsx(Typography, { variant: 'body_small', color: 'secondary', className: 'embedded-delegated-view__approval-description', children: t('dyn_wallet_delegation.revoke_note') })] }) }));
    // Success state content
    const successContent = (jsx("div", { className: 'embedded-delegated-view__body__description', children: jsxs("div", { className: 'embedded-delegated-view__approval-section', children: [jsx("div", { className: 'embedded-delegated-view__approval-icon', children: jsx(SvgCheck, {}) }), jsx(Typography, { variant: 'body_small', weight: 'bold', color: 'primary', className: 'embedded-delegated-view__approval-title', children: t('dyn_wallet_delegation.permissions_granted', { appName }) }), jsx(Typography, { variant: 'body_small', color: 'secondary', className: 'embedded-delegated-view__approval-description', children: t('dyn_wallet_delegation.revoke_note') })] }) }));
    // Error state content
    const errorContent = (jsx("div", { className: 'embedded-delegated-view__body__description', children: jsxs("div", { className: 'embedded-delegated-view__approval-section', children: [jsx("div", { className: 'embedded-delegated-view__error-icon', children: jsx(SvgClose, {}) }), jsx(Typography, { variant: 'body_small', weight: 'bold', color: 'primary', className: 'embedded-delegated-view__approval-title', children: t('dyn_wallet_delegation.something_went_wrong') }), jsx(Typography, { variant: 'body_small', color: 'secondary', className: 'embedded-delegated-view__approval-description', children: t('dyn_wallet_delegation.delegation_timeout_message') })] }) }));
    // Initial state content
    const initialContent = (jsx("div", { className: 'embedded-delegated-view__body__description', children: jsxs("div", { className: 'embedded-delegated-view__approval-section', children: [jsx("div", { className: 'embedded-delegated-view__approval-icon', children: jsx(SvgSwitchHorizontal, {}) }), jsx(Typography, { variant: 'body_small', weight: 'bold', color: 'primary', className: 'embedded-delegated-view__approval-title', copykey: 'dyn_wallet_delegation.approval_required', children: requiresDelegation
                        ? t('dyn_wallet_delegation.approval_required')
                        : t('dyn_wallet_delegation.approval_requested') }), jsx(Typography, { variant: 'body_small', color: 'secondary', className: 'embedded-delegated-view__approval-description', copykey: 'dyn_wallet_delegation.approval_description', children: t('dyn_wallet_delegation.approval_description', {
                        appName,
                    }) })] }) }));
    // Single wallet view
    const displaySingleWallet = () => {
        const [wallet] = waasWallets;
        if (!wallet)
            return null;
        return (jsxs("div", { className: 'embedded-delegated-view__wallet-card-container', children: [jsxs("div", { className: 'embedded-delegated-view__wallet-card', children: [jsx(Typography, { variant: 'body_normal', weight: 'medium', color: 'primary', children: t('dyn_wallet_delegation.my_wallet') }), jsxs("div", { className: 'embedded-delegated-view__wallet-address', children: [jsx("div", { className: 'embedded-delegated-view__wallet-address-dot' }), jsxs(Typography, { variant: 'body_small', color: 'secondary', children: [wallet.address.slice(0, 6), "...", wallet.address.slice(-4)] })] })] }), jsx(AgreementSection, { checked: agreementChecked, onToggle: () => setAgreementChecked(!agreementChecked), text: t('dyn_wallet_delegation.agreement_text') })] }));
    };
    // Multi-wallet initial view
    const displayMultiWalletSummary = () => (jsxs("div", { className: 'embedded-delegated-view__wallet-card-container', children: [jsxs("div", { className: 'embedded-delegated-view__wallet-card', children: [jsxs("div", { className: 'embedded-delegated-view__wallet-card-header', children: [jsx(Typography, { variant: 'body_normal', weight: 'medium', color: 'primary', children: t(selectedWallets.size === waasWallets.length
                                    ? 'dyn_wallet_delegation.all_wallets'
                                    : 'dyn_wallet_delegation.selected_wallets') }), selectedWallets.size !== waasWallets.length && (jsx(Typography, { variant: 'body_normal', color: 'tertiary', children: selectedWallets.size.toString().padStart(2, '0') }))] }), jsx("button", { onClick: () => setShowEditView(true), className: 'embedded-delegated-view__edit-selections-button', children: jsx(Typography, { variant: 'body_small', color: 'secondary', children: t('dyn_wallet_delegation.edit_selections') }) })] }), jsx(AgreementSection, { checked: agreementChecked, onToggle: () => setAgreementChecked(!agreementChecked), text: t('dyn_wallet_delegation.agreement_text') })] }));
    // Edit view (full wallet selection)
    const displayWaasWallets = () => (jsxs("div", { className: 'embedded-delegated-view__wallet-selection', children: [jsxs("div", { className: 'embedded-delegated-view__wallet-selection__header', children: [jsxs("div", { className: 'embedded-delegated-view__wallet-selection__header-text', children: [jsx(Typography, { variant: 'body_small', color: 'secondary', children: t('dyn_wallet_delegation.selected_wallets') }), jsx(Typography, { variant: 'body_small', color: 'tertiary', children: selectedWallets.size.toString().padStart(2, '0') })] }), jsx("button", { onClick: selectedWallets.size === waasWallets.length
                            ? handleDeselectAll
                            : handleSelectAll, className: 'embedded-delegated-view__wallet-selection__deselect-all', children: jsx(Typography, { variant: 'body_small', color: 'tertiary', children: getSelectButtonText() }) })] }), jsx("div", { className: 'embedded-delegated-view__wallet-list', children: waasWallets === null || waasWallets === void 0 ? void 0 : waasWallets.map((wallet) => {
                    var _a, _b;
                    return (jsx("div", { className: `embedded-delegated-view__wallet-item${selectedWallets.has(wallet.id)
                            ? ' embedded-delegated-view__wallet-item--selected'
                            : ''}`, onClick: () => handleWalletToggle(wallet.id), children: jsxs("div", { className: 'embedded-delegated-view__wallet-item__content', children: [jsx("div", { className: 'embedded-delegated-view__wallet-item__icon', children: jsx(WalletIconWithNetwork, { walletKey: wallet.key, Icon: null, iconUrl: (_b = (_a = wallet.connector) === null || _a === void 0 ? void 0 : _a.metadata) === null || _b === void 0 ? void 0 : _b.icon, chainName: wallet.chain, iconSize: 24, showNetwork: true }) }), jsx("div", { className: 'embedded-delegated-view__wallet-item__info', children: jsxs(Typography, { variant: 'body_small', weight: 'medium', children: [wallet.address.slice(0, 6), "...", wallet.address.slice(-4)] }) }), jsx("div", { className: 'embedded-delegated-view__wallet-item__checkbox', children: jsx(Checkbox, { checked: selectedWallets.has(wallet.id), onChange: (e) => e.stopPropagation(), value: wallet.id }) })] }) }, wallet.id));
                }) })] }));
    const navigationButton = showEditView || showLearnMoreView ? (jsx(IconButton, { onClick: () => {
            setShowEditView(false);
            setShowLearnMoreView(false);
            // Reset agreement when coming back from edit view
            setAgreementChecked(false);
        }, type: 'button', children: jsx(SvgArrowLeft, {}) })) : (jsx(IconButton, { onClick: () => {
            // Mark prompt as dismissed until logout (unified state + legacy)
            const state = StorageService.getItem(DELEGATION_STATE) || { completed: {}, denied: {}, dismissed: false };
            state.dismissed = true;
            StorageService.setItem(DELEGATION_STATE, state);
            // No legacy mirror; unified state only
            setShowAuthFlow(false);
        }, type: 'button', children: jsx(SvgClose, {}) }));
    const learnMoreButton = (jsx(IconButton, { onClick: () => setShowLearnMoreView(true), type: 'button', children: jsx(SvgQuestionMark, {}) }));
    const learnMoreContent = () => (jsxs("div", { className: 'embedded-delegated-view__learn-more-content', children: [jsx("div", { className: 'embedded-delegated-view__learn-more-content-icon', children: jsx(SvgQuestion, {}) }), jsx(Typography, { variant: 'body_normal', color: 'secondary', className: 'embedded-delegated-view__learn-more-content-description', children: t('dyn_wallet_delegation.learn_more_description') })] }));
    // Determine which content to show based on state
    const getContentHeader = () => {
        if (isLoading)
            return loadingContent;
        if (isSuccess)
            return successContent;
        if (error)
            return errorContent;
        return initialContent;
    };
    // Determine which buttons to show based on state
    const getButtons = () => {
        if (showLearnMoreView) {
            return (jsx(TypographyButton, { buttonPadding: 'medium', buttonVariant: 'secondary', typographyProps: {
                    color: 'primary',
                    weight: 'medium',
                }, onClick: () => {
                    setShowLearnMoreView(false);
                    setShowEditView(false);
                    setAgreementChecked(false);
                }, dataTestId: 'embedded-delegation-okay-button', copykey: 'dyn_wallet_delegation.learn_more_okay_button', style: {
                    backgroundColor: 'var(--dynamic-base-2)',
                    border: 'var(--px-to-rem-1) solid var(--dynamic-base-4)',
                    width: '100%',
                }, className: 'embedded-delegated-view__body__button', expanded: true, children: t('dyn_wallet_delegation.learn_more_okay_button') }));
        }
        if (isSuccess) {
            return (jsx(TypographyButton, { buttonPadding: 'medium', buttonVariant: 'brand-primary', typographyProps: {
                    color: 'primary',
                    weight: 'bold',
                }, onClick: () => setShowAuthFlow(false), dataTestId: 'embedded-delegation-done-button', copykey: 'dyn_wallet_delegation.done_button', style: {
                    backgroundColor: 'var(--dynamic-base-2)',
                    border: 'var(--px-to-rem-1) solid var(--dynamic-base-4)',
                    width: '100%',
                }, className: 'embedded-delegated-view__body__button', expanded: true, children: t('dyn_wallet_delegation.done_button') }));
        }
        if (error) {
            return (jsx(TypographyButton, { buttonPadding: 'medium', buttonVariant: 'brand-primary', typographyProps: {
                    color: 'primary',
                    weight: 'bold',
                }, onClick: () => handleDelegateWallets(), dataTestId: 'embedded-delegation-try-again-button', copykey: 'dyn_wallet_delegation.try_again_button', style: {
                    backgroundColor: 'var(--dynamic-base-2)',
                    border: 'var(--px-to-rem-1) solid var(--dynamic-base-4)',
                    width: '100%',
                }, className: 'embedded-delegated-view__body__button', expanded: true, children: t('dyn_wallet_delegation.try_again_button') }));
        }
        // If in edit view, show Done button
        if (showEditView) {
            return (jsx(TypographyButton, { buttonPadding: 'medium', buttonVariant: 'secondary', typographyProps: {
                    color: 'primary',
                    weight: 'medium',
                }, onClick: () => {
                    setShowEditView(false);
                    setAgreementChecked(false);
                    setShowLearnMoreView(false);
                }, dataTestId: 'embedded-delegation-done-button', copykey: 'dyn_wallet_delegation.done_button', style: {
                    backgroundColor: 'var(--dynamic-base-2)',
                    border: 'var(--px-to-rem-1) solid var(--dynamic-base-4)',
                    width: '100%',
                }, className: 'embedded-delegated-view__body__button', expanded: true, children: t('dyn_wallet_delegation.done_button') }));
        }
        return (jsxs(Fragment, { children: [jsx(TypographyButton, { buttonPadding: 'medium', buttonVariant: 'brand-primary', typographyProps: {
                        color: 'inherit',
                    }, onClick: () => handleDelegateWallets(), loading: isLoading, disabled: selectedWallets.size === 0 || !agreementChecked, dataTestId: 'embedded-delegation-button', copykey: 'dyn_wallet_delegation.approve_button', style: { width: '100%' }, className: 'embedded-delegated-view__body__button', expanded: true, children: t('dyn_wallet_delegation.approve_button') }), !isLoading && !requiresDelegation && (jsx(TypographyButton, { buttonPadding: 'medium', buttonVariant: 'brand-primary', typographyProps: {
                        color: 'primary',
                        weight: 'bold',
                    }, onClick: () => handleDenySelectedWallets(), dataTestId: 'embedded-delegation-deny-button', copykey: 'dyn_wallet_delegation.deny_button', style: {
                        backgroundColor: 'var(--dynamic-base-2)',
                        border: 'var(--px-to-rem-1) solid var(--dynamic-base-4)',
                        width: '100%',
                    }, className: 'embedded-delegated-view__body__button embedded-delegated-view__body__deny-button', expanded: true, children: t('dyn_wallet_delegation.deny_button') })), !isLoading && requiresDelegation && (jsx(TypographyButton, { buttonPadding: 'medium', buttonVariant: 'brand-primary', typographyProps: {
                        color: 'primary',
                        weight: 'bold',
                    }, onClick: () => {
                        handleLogOut();
                    }, dataTestId: 'embedded-delegation-logout-button', copykey: 'dyn_wallet_delegation.logout_button', style: {
                        backgroundColor: 'var(--dynamic-base-2)',
                        border: 'var(--px-to-rem-1) solid var(--dynamic-base-4)',
                        width: '100%',
                    }, className: 'embedded-delegated-view__body__button embedded-delegated-view__body__logout-button', expanded: true, children: t('dyn_wallet_delegation.logout_button') }))] }));
    };
    // Header configuration
    let headerLeading;
    let headerTrailing;
    if (showEditView || showLearnMoreView) {
        headerLeading = navigationButton;
        headerTrailing = undefined;
    }
    else {
        // Only show learn more button on initial screen (not loading, success, or error states)
        if (!isLoading && !isSuccess && !error) {
            headerTrailing = learnMoreButton;
        }
        if (!requiresDelegation) {
            headerLeading = navigationButton;
        }
        else {
            headerLeading = undefined;
        }
    }
    const getHeaderChildren = () => {
        if (showEditView) {
            return (jsx(Typography, { variant: 'body_normal', weight: 'bold', color: 'primary', children: t('dyn_wallet_delegation.edit_wallets_to_delegate') }));
        }
        if (showLearnMoreView) {
            return (jsx(Typography, { variant: 'body_normal', weight: 'bold', color: 'primary', children: t('dyn_wallet_delegation.learn_more') }));
        }
        return undefined;
    };
    const headerChildren = getHeaderChildren();
    return (jsxs(Fragment, { children: [jsx(ModalHeader, { leading: headerLeading, trailing: headerTrailing, style: {
                    paddingBottom: showEditView || showLearnMoreView ? '24px' : 0,
                }, children: headerChildren }), jsx("div", { className: 'embedded-delegated-view', children: jsxs("div", { className: 'embedded-delegated-view__body', children: [!showEditView && !showLearnMoreView && getContentHeader(), errorText && jsx(ErrorContainer, { children: errorText }), !isLoading && !isSuccess && !error && (jsx("div", { className: 'embedded-delegated-view__body__card', children: (() => {
                                if (showEditView)
                                    return displayWaasWallets();
                                if (showLearnMoreView)
                                    return learnMoreContent();
                                if (waasWallets.length === 1)
                                    return displaySingleWallet();
                                if (waasWallets.length > 1)
                                    return displayMultiWalletSummary();
                                return null;
                            })() })), jsx("div", { className: 'embedded-delegated-view__body__button_section', children: getButtons() })] }) })] }));
};

export { WalletDelegationView };
