import {useState, useRef, useEffect, useMemo} from "@wordpress/element";
import {copyToClipboard} from "../../../../components/chatbots/includes/helpers";

export default function Notice({title, desc, type = 'default', dismissible = true, children, style}) {
    const [show, setShow] = useState(true);
    const copiedTimeoutsRef = useRef({});
    const noticeBodyRef = useRef(null);

    // Process description to add copy buttons to each code element
    const processedDesc = useMemo(() => {
        if (!desc) return desc;

        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = desc;
        const codeElements = tempDiv.querySelectorAll('code');

        if (codeElements.length === 0) {
            return desc;
        }

        // Replace each code element with code + copy button
        codeElements.forEach((codeEl, index) => {
            const codeText = codeEl.textContent.trim();
            // Create stable ID based on index and code text hash
            const codeId = `code-${index}-${codeText.substring(0, 10).replace(/\s/g, '-')}`;

            // Create wrapper
            const wrapper = document.createElement('span');
            wrapper.style.display = 'inline-flex';
            wrapper.style.alignItems = 'center';
            wrapper.style.gap = '4px';
            wrapper.className = 'lbaic-settings-notice-code-wrapper';

            // Keep the original code element
            const codeClone = codeEl.cloneNode(true);
            wrapper.appendChild(codeClone);

            // Create copy button
            const copyButton = document.createElement('button');
            copyButton.type = 'button';
            copyButton.className = 'lbaic-settings-button-reset lbaic-settings-notice-code-copy';
            copyButton.setAttribute('data-code-id', codeId);
            copyButton.setAttribute('data-code-text', codeText);
            copyButton.innerHTML = `
                <svg class="lbaic-settings-notice-code-copy-i" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <use href="#lbaic-settings-chats-copy"/>
                </svg>
            `;
            wrapper.appendChild(copyButton);

            // Replace original code with wrapper
            codeEl.parentNode.replaceChild(wrapper, codeEl);
        });

        return tempDiv.innerHTML;
    }, [desc]);

    // Cleanup timeouts on unmount
    useEffect(() => {
        return () => {
            Object.values(copiedTimeoutsRef.current).forEach(timeout => {
                if (timeout) clearTimeout(timeout);
            });
        };
    }, []);

    // Handle copy button clicks and update visual feedback
    useEffect(() => {
        if (!processedDesc || !show || !noticeBodyRef.current) return;

        const handleCopyClick = async (e) => {
            const button = e.target.closest('.lbaic-settings-notice-code-copy');
            if (!button) return;

            e.preventDefault();
            e.stopPropagation();

            const codeText = button.getAttribute('data-code-text');
            const codeId = button.getAttribute('data-code-id');

            if (!codeText) return;

            const res = await copyToClipboard(codeText);
            if (res.success) {
                // Update button visual feedback
                button.classList.add('lbaic-settings-notice-code-copied');
                const svg = button.querySelector('svg use');
                if (svg) {
                    svg.setAttribute('href', '#lbaic-settings-check');
                }

                // Clear any existing timeout for this code
                if (copiedTimeoutsRef.current[codeId]) {
                    clearTimeout(copiedTimeoutsRef.current[codeId]);
                }

                // Reset copied state after 2 seconds
                copiedTimeoutsRef.current[codeId] = setTimeout(() => {
                    button.classList.remove('lbaic-settings-notice-code-copied');
                    if (svg) {
                        svg.setAttribute('href', '#lbaic-settings-chats-copy');
                    }
                    delete copiedTimeoutsRef.current[codeId];
                }, 2000);
            } else {
                console.warn('Failed to copy to clipboard:', res.error);
            }
        };

        const noticeBody = noticeBodyRef.current;
        noticeBody.addEventListener('click', handleCopyClick);
        return () => {
            noticeBody.removeEventListener('click', handleCopyClick);
        };
    }, [processedDesc, show]);

    let noticeIconId = `#lbaic-settings-notice-${type}`;
    if (type === 'warning') {
        noticeIconId = '#lbaic-settings-info';
    }

    return show ? <div className="lbaic-settings-row">
        <div className={`lbaic-settings-notice ${type}`} style={style}>
            <div className="lbaic-settings-notice-in">
                <div className="lbaic-settings-notice-i-container">
                    <svg className="lbaic-settings-notice-i"
                         xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <use href={noticeIconId}/>
                    </svg>
                </div>
                <div className="lbaic-settings-notice-body" ref={noticeBodyRef}>
                    {title?.length > 0 && (
                        <p className="lbaic-settings-notice-title" dangerouslySetInnerHTML={{__html: title}}/>
                    )}
                    {desc?.length > 0 && (
                        <p className="lbaic-settings-notice-desc" dangerouslySetInnerHTML={{__html: processedDesc}}/>
                    )}
                    {children}
                </div>
            </div>
            {dismissible &&
                <button className="lbaic-settings-button-reset lbaic-settings-notice-action"
                        onClick={() => setShow(false)}>
                    <svg className="lbaic-settings-notice-action-in"
                         xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <use href="#lbaic-settings-notice-close"/>
                    </svg>
                </button>}
        </div>
    </div> : null;
}