import {useContext, useEffect, useState} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import {ChatBotsContext} from "../../../../contexts/chatbots";
import {ANIMATION_TYPES, ICON_COLORS_1, TRIGGER_ANIMATION_TYPE, TRIGGER_ANIMATIONS} from "../_data";
import {getUnseenMessagesCount} from "../../../hooks/use-sound-notification";

export default function Single({toggleChatbots, leadCaptureBlocking}) {
    const chatbotsContext = useContext(ChatBotsContext);
    const [triggerBgIcon, setTriggerBgIcon] = useState('squircle');
    const [triggerIcon, setTriggerIcon] = useState('icon');
    const chatbot = chatbotsContext.chatbots[chatbotsContext.activeChatbotIndex];
    const isChatbotClosed = chatbotsContext.openedChatbotsUUIDs.length === 0;
    // Check if we're in admin preview
    const isAdminPreview = typeof document !== 'undefined' && document.getElementById('lbaic-chatbot-preview') !== null;

    // Get badge visibility settings
    const showUnseenMessagesBadge = chatbot?.utility?.show_unseen_messages_badge ?? true;
    const showUnseenMessagesCount = chatbot?.utility?.show_unseen_messages_count ?? true;
    const [unseenMessagesCount, setUnseenMessagesCount] = useState(0);

    useEffect(() => {
        // Update background shape
        const shape = chatbot?.utility?.icon_bg_shape;
        if (shape) {
            setTriggerBgIcon(shape);
        }
        // Update icon
        const icon = chatbot?.utility?.icon;
        if (icon) {
            setTriggerIcon(icon);
        }
    }, [chatbotsContext.chatbots, chatbotsContext.activeChatbotIndex, chatbot]);

    // Listen for unseen messages count updates
    useEffect(() => {
        if (!chatbot?.uuid) {
            return;
        }

        // Initialize count from store
        setUnseenMessagesCount(getUnseenMessagesCount(chatbot.uuid));

        // Listen for count updates via hook
        const handleCountUpdate = (updatedUuid, count) => {
            if (updatedUuid === chatbot.uuid) {
                setUnseenMessagesCount(count);
            }
        };

        if (typeof LimbChatbot !== 'undefined' && LimbChatbot?.Hooks?.addAction) {
            LimbChatbot.Hooks.addAction('lbaic.chatbot.unseenMessagesCount', 'lbaic/trigger/unseen-count', handleCountUpdate);
        }

        return () => {
            if (typeof LimbChatbot !== 'undefined' && LimbChatbot?.Hooks?.removeAction) {
                LimbChatbot.Hooks.removeAction('lbaic.chatbot.unseenMessagesCount', 'lbaic/trigger/unseen-count');
            }
        };
    }, [chatbot?.uuid]);

    const handleToggleChatbot = () => {
        if (chatbotsContext.openedChatbotsUUIDs.indexOf(chatbotsContext.chatbots[0].uuid) !== -1) {
            LimbChatbot.Hooks.doAction('lbaic.chatbot.actions.close', chatbotsContext.chatbots[0].uuid);
        } else {
            toggleChatbots([chatbotsContext.chatbots[0].uuid]);
        }
    }

    // Hide trigger in admin preview when chat is open
    if (isAdminPreview && !isChatbotClosed) {
        return null;
    }

    return (
        <div className={`lbaic-trigger ${TRIGGER_ANIMATIONS[TRIGGER_ANIMATION_TYPE].open}${leadCaptureBlocking ? ' lbaic-trigger-disabled' : ''}`}>
            <button className='lbaic-trigger-in' onClick={handleToggleChatbot}
                    aria-label={__("Toggle chatbot", 'limb-chatbot')}>
                <div className='lbaic-trigger-icon'>
                    {showUnseenMessagesBadge && unseenMessagesCount > 0 && (
                        <div className='lbaic-trigger-unseen-messages'>
                            {showUnseenMessagesCount && (
                                <span className='lbaic-trigger-unseen-messages-count'>{unseenMessagesCount}</span>
                            )}
                        </div>
                    )}
                    <svg className='lbaic-trigger-icon-bg' xmlns='http://www.w3.org/2000/svg'>
                        <use href={`#lbaic-trigger-bg-${triggerBgIcon}`} fill='var(--lbaic-trigger-color)'/>
                        <use href={`#lbaic-trigger-bg-${triggerBgIcon}`} className='lbaic-trigger-hover'
                             fill='var(--lbaic-white-100)' fillOpacity='0.2'/>
                        <use href={`#lbaic-trigger-bg-${triggerBgIcon}`} className='lbaic-trigger-active'
                             fill='var(--lbaic-black-100)' fillOpacity='0.2'/>
                    </svg>
                    {/* Chat icon */}
                    <svg className={`lbaic-trigger-icon-in lbaic-trigger-icon-chat${chatbotsContext.openedChatbotsUUIDs?.length ? ' lbaic-trigger-icon-hidden' : ' lbaic-trigger-icon-main'}`} xmlns='http://www.w3.org/2000/svg'>
                        {
                            ANIMATION_TYPES[triggerIcon] === 1 ? (
                                <>
                                    <use
                                        href={`#lbaic-${('chatbot-icon-' + triggerIcon + '-shape')}`}
                                        fill={`${ICON_COLORS_1[triggerIcon].shape}`}/>
                                    <use
                                        href={`#lbaic-${('chatbot-icon-' + triggerIcon + '-left')}`}
                                        fill={`${ICON_COLORS_1[triggerIcon].left}`}/>
                                    <use
                                        href={`#lbaic-${('chatbot-icon-' + triggerIcon + '-center')}`}
                                        fill={`${ICON_COLORS_1[triggerIcon].center}`}/>
                                    <use
                                        href={`#lbaic-${('chatbot-icon-' + triggerIcon + '-right')}`}
                                        fill={`${ICON_COLORS_1[triggerIcon].right}`}/>
                                </>
                            ) : ANIMATION_TYPES[triggerIcon] === 2 ? (
                                <>
                                    <use
                                        href={`#lbaic-${('chatbot-icon-' + triggerIcon + '-first')}`}
                                        fill='var(--lbaic-white-100)'/>
                                    <use
                                        href={`#lbaic-${('chatbot-icon-' + triggerIcon + '-last')}`}
                                        fill='var(--lbaic-white-100)'/>
                                </>
                            ) : ANIMATION_TYPES[triggerIcon] === 3 ? (
                                <>
                                    <use
                                        href={`#lbaic-${('chatbot-icon-' + triggerIcon + '-shape')}`}
                                        fill={`${ICON_COLORS_1[triggerIcon].shape}`}/>
                                    <use
                                        href={`#lbaic-${('chatbot-icon-' + triggerIcon + '-line')}`}
                                        fill={`${ICON_COLORS_1[triggerIcon].center}`}/>
                                    <use
                                        href={`#lbaic-${('chatbot-icon-' + triggerIcon + '-line-2')}`}
                                        fill={`${ICON_COLORS_1[triggerIcon].center}`}/>
                                </>
                            ) : (
                                <use
                                    href={`#lbaic-${('chatbot-icon-' + triggerIcon)}`}
                                    fill='var(--lbaic-white-100)'/>
                            )
                        }
                    </svg>
                    {/* Close icon */}
                    <svg
                        className={`lbaic-trigger-icon-in lbaic-trigger-icon-close${chatbotsContext.openedChatbotsUUIDs?.length ? '' : ' lbaic-trigger-icon-hidden'}`}
                        xmlns='http://www.w3.org/2000/svg'
                    >
                        <use href="#lbaic-trigger-close" fill='var(--lbaic-white-100)'/>
                    </svg>
                </div>
            </button>
        </div>
    )
}