'use client'
import { useState, useRef, useCallback } from 'react';
import { DynamicError } from '@dynamic-labs/utils';
import '@dynamic-labs/iconic';
import '@dynamic-labs/wallet-connector-core';
import 'react/jsx-runtime';
import '../../../context/ViewContext/ViewContext.js';
import '../../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '../../constants/colors.js';
import '../../constants/values.js';
import '@dynamic-labs/sdk-api-core';
import { usePreventPageScroll } from '../../../shared/utils/hooks/usePreventPageScroll/usePreventPageScroll.js';
import '../../../shared/consts/index.js';

const useConfirmationPortal = ({ onResolve, onReject, defaultErrorMessage, }) => {
    usePreventPageScroll(true);
    const [show, setShow] = useState(true);
    const errorRef = useRef(null);
    const successResponseRef = useRef(null);
    const closeModal = useCallback(() => {
        setShow(false);
    }, [setShow]);
    const handleOnModalUnmount = useCallback(() => {
        if (successResponseRef.current) {
            return onResolve(successResponseRef.current);
        }
        const error = errorRef.current ||
            new DynamicError(defaultErrorMessage || 'Something went wrong', 'defaulterrormessage_something_went_wrong');
        return onReject(error);
    }, [onResolve, onReject, defaultErrorMessage]);
    const onSuccess = (response, closePortal = true) => {
        errorRef.current = null;
        successResponseRef.current = response;
        if (closePortal) {
            closeModal();
        }
    };
    const onError = (error, closePortal = false) => {
        successResponseRef.current = null;
        errorRef.current = error;
        if (closePortal) {
            closeModal();
        }
    };
    return {
        closeModal,
        handleOnModalUnmount,
        onError,
        onSuccess,
        show,
    };
};

export { useConfirmationPortal };
