import {createPortal, useEffect, useRef, useState} from "@wordpress/element";
import ChatbotsGroups from "../../../../../../../components/chatbot-groups";
import ToggleChatbotPreview from "../../../../../_components/chatbot/toggle-preview";

/**
 * Get chatbot preview storage key
 *
 * @param {number} userId User ID
 * @return {string}
 */
export const getChatbotPreviewStorageKey = (userId) => {
    const prefix = 'lbaic.settings.chatbot.preview'
    return userId ? prefix + '.' + userId : prefix;
}

export default function ChatbotPreview({uuid = 'default', open, domNode, userId, chatbotPreviewToggled}) {
    const previewStorageKey = useRef(getChatbotPreviewStorageKey(userId));

    const [show, setShow] = useState(() => {
        const storedValue = localStorage.getItem(previewStorageKey.current);
        return storedValue === 'true' || storedValue === null;
    });

    useEffect(() => {
        previewStorageKey.current = getChatbotPreviewStorageKey(userId);
        const localStorageData = localStorage.getItem(previewStorageKey.current);
        const newShow = localStorageData === 'true' || localStorageData === null;
        setShow(newShow);
    }, [userId]);

    const handleShowUpdate = (newShow) => {
        if (!newShow || !window.lbaicSkipChatbotPreviewOnRedirect) {
            setShow(newShow);
        }
        // Update local storage
        localStorage.setItem(previewStorageKey.current, newShow);

        chatbotPreviewToggled && chatbotPreviewToggled(newShow);
    }

    return (
        <>
            {show && createPortal(
                <ChatbotsGroups
                    id={uuid !== 'default' ? uuid : null}
                    autoOpen={open && uuid}
                    attributes={{preview: true, uuid}}
                />,
                domNode || document.getElementById('lbaic-chatbot-preview')
            )}
            <ToggleChatbotPreview
                show={show}
                setShow={handleShowUpdate}
            />
        </>
    );
}