import {createPortal, useEffect, useRef} from '@wordpress/element';
import LoadingBar from "../../fields/loading-bar";

/**
 * Close chatbot preview if the popup covers it
 *
 * @param {HTMLElement} popupEl Popup element
 */
const closeChatbotPreviewIfPopupCoversIt = (popupEl) => {
    const chatbotPreviewEl = document.getElementById('lbaic-chatbot-preview');
    if (!chatbotPreviewEl) {
        return;
    }

    const chatbotTriggerEl = chatbotPreviewEl.querySelector('.lbaic-trigger');
    const chatbotEl = chatbotPreviewEl.querySelector('.lbaic-grid');

    if (!popupEl || (!chatbotEl && !chatbotTriggerEl)) {
        return;
    }

    const adminPageElement = document.getElementById('lbaic-admin-page-settings');
    if (!adminPageElement) {
        return;
    }

    const isLargeScreen = window.innerWidth >= 768

    if (!isLargeScreen) {
        return;
    }

    const popupRect = popupEl.getBoundingClientRect();
    const chatbotRect = chatbotTriggerEl?.getBoundingClientRect() || chatbotEl?.getBoundingClientRect();

    const overlap = !(
        popupRect.right <= chatbotRect.left ||
        popupRect.left >= chatbotRect.right ||
        popupRect.bottom <= chatbotRect.top ||
        popupRect.top >= chatbotRect.bottom
    );

    return overlap;
}

export const isChatbotInitiallyClosed = () => {
    const chatbotPreviewEl = document.getElementById('lbaic-chatbot-preview');
    if (!chatbotPreviewEl) {
        return true;
    }

    const chatbotTriggerEl = chatbotPreviewEl.querySelector('.lbaic-trigger');
    const chatbotEl = chatbotPreviewEl.querySelector('.lbaic-grid');

    return !chatbotEl && !chatbotTriggerEl;
}

export default function PopupContainer({
                                           title,
                                           headerIcon,
                                           description,
                                           close,
                                           loading,
                                           showLoadingContainer,
                                           layoutStyle,
                                           style,
                                           popupClassName,
                                           bodyClassName,
                                           children,
                                           headerActions,
                                           divider,
                                           footer,
                                           checkChatbotPreviewPosition = true
                                       }) {
    const popupRef = useRef(null);
    const childrenChangeTimeoutRef = useRef(null);
    const initiallyClosedRef = useRef(isChatbotInitiallyClosed());
    const closedRef = useRef(false);

    useEffect(() => {
        return () => {
            if (closedRef.current && !initiallyClosedRef.current) {
                LimbChatbot.Hooks.doAction('lbaic.settings.chatbot.preview.show', true);
            }
        }
    }, []);

    useEffect(() => {
        if (!checkChatbotPreviewPosition || initiallyClosedRef.current) {
            return;
        }

        const chatbotPreviewEl = document.getElementById('lbaic-chatbot-preview');
        if (!chatbotPreviewEl) {
            return;
        }

        const check = () => {
            const overlap = closeChatbotPreviewIfPopupCoversIt(popupRef.current);
            // Close/open
            if (!closedRef.current) {
                if (overlap) {
                    LimbChatbot.Hooks.doAction('lbaic.settings.chatbot.preview.show', true);
                } else {
                    LimbChatbot.Hooks.doAction('lbaic.settings.chatbot.preview.show', false);
                }
            }
        }

        window.addEventListener('resize', check);

        return () => {
            window.removeEventListener('resize', check);
        }
    }, [checkChatbotPreviewPosition]);

    useEffect(() => {
        if (!checkChatbotPreviewPosition || initiallyClosedRef.current) {
            return;
        }

        clearTimeout(childrenChangeTimeoutRef.current);

        childrenChangeTimeoutRef.current = setTimeout(() => {
            const overlap = closeChatbotPreviewIfPopupCoversIt(popupRef.current);
            if (overlap) {
                if (!closedRef.current) {
                    LimbChatbot.Hooks.doAction('lbaic.settings.chatbot.preview.show', false);
                    closedRef.current = true;
                }
            } else {
                if (!closedRef.current) {
                    LimbChatbot.Hooks.doAction('lbaic.settings.chatbot.preview.show', true);
                }
            }
        }, 0);

        return () => {
            clearTimeout(childrenChangeTimeoutRef.current);
        }
    }, [checkChatbotPreviewPosition, children])

    return createPortal(<div className="lbaic-settings-popup-layout" style={layoutStyle}>
        <div className='lbaic-settings-popup-overlay' onClick={close}/>
        <div
            ref={popupRef}
            className={`lbaic-settings-popup${popupClassName ? ' ' + popupClassName : ''}`}
            style={style}
        >
            <div className='lbaic-settings-popup-in'>
                <div className='lbaic-settings-popup-header'>
                    <div className='lbaic-settings-popup-header-in'>
                        <div className='lbaic-settings-popup-header-content'>
                            {headerIcon && (
                                <svg
                                    className="lbaic-settings-popup-header-icon"
                                    xmlns="http://www.w3.org/2000/svg"
                                    fill="none"
                                    viewBox="0 0 24 24">
                                    <use href={`#lbaic-settings-${headerIcon}`}></use>
                                </svg>
                            )}
                            <h6 className='lbaic-settings-popup-header-label'
                                dangerouslySetInnerHTML={{__html: title}}/>
                            {headerActions && (
                                <div className='lbaic-settings-popup-header-actions'>{headerActions}</div>
                            )}
                        </div>
                        {description?.length > 0 && (
                            <p className='lbaic-settings-popup-header-desc'
                               dangerouslySetInnerHTML={{__html: description}}/>
                        )}
                    </div>
                </div>
                {children &&
                    <>
                        {divider || (
                            <div
                                className='lbaic-settings-divider lbaic-settings-divider-popup lbaic-settings-divider-loading'>
                                {loading && <LoadingBar/>}
                            </div>
                        )}
                        <div className={`lbaic-settings-popup-body${bodyClassName ? ' ' + bodyClassName : ''}`}>
                            {showLoadingContainer && <div className="lbaic-settings-popup-loading"/>}
                            <div
                                className='lbaic-settings-popup-body-in lbaic-settings-scroll-y lbaic-settings-scroll-color'>
                                {children}
                            </div>
                        </div>
                    </>}
                {footer &&
                    <div className='lbaic-settings-popup-footer'>
                        {footer}
                    </div>}
            </div>
        </div>
    </div>, document.getElementById('lbaic-settings-popup'));
}