import {cloneElement, useEffect, useRef, useState} from "@wordpress/element";
import {__} from "@wordpress/i18n";

export default function SourcesPopover({sources, children, arrowPosition = 'left'}) {
    const [isOpen, setIsOpen] = useState(false);
    const triggerRef = useRef(null);

    useEffect(() => {
        if (!isOpen) {
            return;
        }

        const handleClickOutside = (event) => {
            if (
                triggerRef.current &&
                !triggerRef.current.contains(event.target) &&
                !event.target.closest('.lbaic-message-sources-popover')
            ) {
                setIsOpen(false);
            }
        };

        // Use a small delay to allow the click event to register
        const timeoutId = setTimeout(() => {
            document.addEventListener('mousedown', handleClickOutside);
        }, 0);

        return () => {
            clearTimeout(timeoutId);
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, [isOpen]);

    const handleToggle = (e) => {
        e.stopPropagation();
        setIsOpen(!isOpen);
    };

    // Clone the child element and attach ref and onClick handler
    const childrenWithProps = cloneElement(children, {
        onClick: handleToggle,
        ref: triggerRef,
    });

    const popoverClassName = `lbaic-message-sources-popover lbaic-message-sources-popover-p-top lbaic-message-sources-popover-a-${arrowPosition}`;

    return (
        <>
            {childrenWithProps}
            <div className={popoverClassName}>
                <div className={`lbaic-message-sources-popover-in${isOpen ? '' : ' hide'}`}>
                    <div className="lbaic-message-sources-popover-inner">
                        {sources.map((source, index) => (
                            <a
                                key={index}
                                href={source.source_url || '#'}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="lbaic-message-sources-popover-link"
                            >
                                <span dangerouslySetInnerHTML={{__html: source.name || (__("Knowledge", 'limb-chatbot') + ' ' + (index + 1))}}></span>
                                <svg className="lbaic-intro-row-icon" xmlns="http://www.w3.org/2000/svg" fill="none"
                                     viewBox="0 0 24 24">
                                    <use href="#lbaic-arrow" className="lbaic-arrow"></use>
                                    <use href="#lbaic-external-box"></use>
                                </svg>
                            </a>
                        ))}
                    </div>
                </div>
            </div>
        </>
    );
}