import {useEffect, useRef, useState} from "@wordpress/element";
import {CONTENT_TAB_ARROW} from "./_data";

export default function ContentTabs({currentTab, children}) {
    const scrollRef = useRef(null);
    const [hideLeftArrow, setHideLeftArrow] = useState(true);
    const [hideRightArrow, setHideRightArrow] = useState(true);

    useEffect(() => {
        const el = scrollRef.current;
        if (!el) {
            return;
        }
        checkScroll();

        el.addEventListener('scroll', checkScroll);
        window.addEventListener('resize', checkScroll);

        return () => {
            el.removeEventListener('scroll', checkScroll);
            window.removeEventListener('resize', checkScroll);
        };
    }, [children]);

    useEffect(() => {
        if (currentTab && scrollRef.current) {
            // Keep the current tab visible section
            const scrollElRect = scrollRef.current.getBoundingClientRect();
            if (currentTab.right > scrollElRect.right) {
                scrollRef.current.scrollBy({left: currentTab.right - scrollElRect.right + CONTENT_TAB_ARROW.right.width, behavior: 'smooth'});
            } else if (currentTab.left < scrollElRect.left) {
                scrollRef.current.scrollBy({left: -(scrollElRect.left - currentTab.left + CONTENT_TAB_ARROW.left.width), behavior: 'smooth'});
            }
        }
    }, [currentTab]);

    const checkScroll = () => {
        const el = scrollRef.current;
        if (!el) {
            return;
        }

        setHideLeftArrow(el.scrollLeft < 1);
        setHideRightArrow((el.scrollLeft + el.clientWidth) > (el.scrollWidth - 1));
    };

    const scrollLeft = () => {
        scrollRef.current.scrollBy({left: -200, behavior: 'smooth'});
    };

    const scrollRight = () => {
        scrollRef.current.scrollBy({left: 200, behavior: 'smooth'});
    };

    return <div className='lbaic-settings-content-tabs'>
        <button className={`lbaic-settings-tab-arrows backward${hideLeftArrow ? ' hide' : ''}`} onClick={scrollLeft}>
            <svg className='lbaic-settings-tab-arrows-i' xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 16 16'>
                <use href='#lbaic-settings-tab-arrow'/>
            </svg>
        </button>
        <div ref={scrollRef} className='lbaic-settings-tab-group lbaic-settings-scroll-x lbaic-settings-scroll-style lbaic-settings-divider'>
            {children}
        </div>
        <button className={`lbaic-settings-tab-arrows forward${hideRightArrow ? ' hide' : ''}`} onClick={scrollRight}>
            <svg className='lbaic-settings-tab-arrows-i' xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 16 16'>
                <use href='#lbaic-settings-tab-arrow'/>
            </svg>
        </button>
    </div>
}