import {createPortal, useEffect, useState} from '@wordpress/element';
import {__} from '@wordpress/i18n';
import ToggleButton from "../../../fields/toggle-button";

export default function ToggleChatbotPreview({show, setShow}) {
    const [container, setContainer] = useState(null);

    useEffect(() => {
        const screenMetaLinks = document.getElementById('screen-meta-links');

        if (screenMetaLinks) {
            const wrapper = document.createElement('div');
            wrapper.setAttribute('id', 'lbaic-chatbot-preview-link-wrap');
            wrapper.className = 'hide-if-no-js screen-meta-toggle';
            screenMetaLinks.appendChild(wrapper);
            setContainer(wrapper);

            return () => {
                wrapper.remove();
            };
        }
    }, []);

    useEffect(() => {
        LimbChatbot.Hooks.addAction('lbaic.settings.chatbot.preview.show', 'lbaic/settings/chatbot/preview/show', (v) => {
            setShow(v);
        });

        return () => {
            LimbChatbot.Hooks.removeAction('lbaic.settings.chatbot.preview.show', 'lbaic/settings/chatbot/preview/show');
        };
    }, []);

    if (!container) {
        return null;
    }

    const handleClick = (e) => {
        e.stopPropagation();
        setShow(!show);
    }

    return (
        createPortal(
            <>
                <button
                    type="button"
                    id="lbaic-chatbot-preview-link"
                    className="button show-settings"
                    aria-controls="lbaic-chatbot-preview-wrap"
                    onClick={handleClick}
                >
                    {__("Preview chatbot", 'limb-chatbot')}
                    <ToggleButton
                        onClick={handleClick}
                        isActive={show}
                    />
                </button>
            </>,
            container
        )
    );
}