import {createContext, createRoot, useContext} from '@wordpress/element';
import {__} from '@wordpress/i18n';
import PopupContainer from "../../containers/popup";

export const ConfirmContext = createContext(null);

export function useConfirm() {
    return useContext(ConfirmContext);
}

export function createConfirm(chatRef) {
    return function confirm(message) {
        return new Promise((resolve) => {
            const container = document.createElement('div');
            document.body.appendChild(container);

            const root = createRoot(container);

            const handleConfirm = () => {
                cleanup();
                resolve(true);
            };

            const handleCancel = () => {
                cleanup();
                resolve(false);
            };

            const cleanup = () => {
                root.unmount();
                container.remove();
            };

            root.render(
                chatRef.current
                    ?
                    <PopupContainer
                        title={message}
                        close={handleCancel}
                        footer={<>
                            <button
                                className='lbaic-button lbaic-button-center lbaic-button-h-40 lbaic-button-secondary'
                                onClick={handleCancel}>
                                <span className='lbaic-button-label'>{__("Cancel", 'limb-chatbot')}</span>
                            </button>
                            <button
                                className='lbaic-button lbaic-button-center lbaic-button-h-40 lbaic-button-primary'
                                onClick={handleConfirm}>
                                <span className='lbaic-button-label'>{__("Confirm", 'limb-chatbot')}</span>
                            </button>
                        </>}
                        rootRef={chatRef}/>
                    : null
            );
        });
    };
}