import {useEffect, useRef} from "@wordpress/element";
import Chat from '../single';
import {SIZE_WIDTH} from "../../includes/constants";

export default function Groups({chatbots, showInSide, openedChatbotsUUIDs, closeChatbots, onChatCloseStart, capturedState}) {
    const gridEl = useRef(null);
    const chatbotsWidths = useRef({});

    useEffect(() => {
        // Events
        window.addEventListener('resize', closeChatbotsOffScreen);

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

    const closeChatbotsOffScreen = () => {
        // Screen size
        const screenWidth = window.innerWidth;
        // In case of mobile screen size
        if (screenWidth < 767.98) {
            // Keep only one chatbot opened
            if (openedChatbotsUUIDs.length > 1) {
                // Close old chatbots
                closeChatbots(openedChatbotsUUIDs.slice(0, -1));
            }
            return;
        }
        // Chatbots grid size
        const rect = gridEl.current?.getBoundingClientRect();
        if (rect) {
            // Get size out of screen
            let outOfScreen = 0;
            if (showInSide === 'left') {
                if (rect.right > screenWidth) {
                    outOfScreen = rect.right - screenWidth;
                } else {
                    // Nothing to do
                    return;
                }
            } else {
                if (rect.left < 0) {
                    outOfScreen = -rect.left;
                } else {
                    // Nothing to do
                    return;
                }
            }
            // Close old chatbots to fit on screen
            const GAP = 10;
            if (openedChatbotsUUIDs.length) {
                let i = 0, sum = 0;
                const closeTheseChatbots = [];
                do {
                    // Close first one
                    closeTheseChatbots.push(openedChatbotsUUIDs[i]);
                    // Check for size
                    if (openedChatbotsUUIDs[i] in chatbotsWidths.current) {
                        sum += GAP + chatbotsWidths.current[openedChatbotsUUIDs[i]];
                    }
                } while (sum < outOfScreen && ++i < openedChatbotsUUIDs.length);
                // Close old chatbots
                if (closeTheseChatbots.length) {
                    closeChatbots(closeTheseChatbots);
                }
            }
        }
    }

    const closeChatbot = (uuid) => {
        closeChatbots([uuid]);
    }

    const chatbotSizeChanged = (uuid, size) => {
        // Update widths state
        chatbotsWidths.current[uuid] = SIZE_WIDTH[size];
        // Close chatbots out of screen
        closeChatbotsOffScreen();
    }

    const renderChatbot = (chatbot) => {
        // Get chatbot
        const uuid = chatbot?.uuid;
        if (uuid) {
            const handleCloseStart = typeof onChatCloseStart === 'function' ? () => onChatCloseStart(uuid, showInSide) : undefined;
            return (
                <Chat
                    key={uuid}
                    chatbot={chatbot}
                    close={closeChatbot}
                    sizeChanged={chatbotSizeChanged}
                    onCloseStart={handleCloseStart}
                    showChatbot={openedChatbotsUUIDs.indexOf(uuid) !== -1}
                    capturedState={capturedState}
                />
            );
        }

        return false;
    }

    if (!chatbots.length) {
        return null;
    }

    return (
        <div ref={gridEl} className='lbaic-grid'>{chatbots.map(renderChatbot)}</div>
    );
}