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

/**
 * NestedTabs component for creating tabbed interfaces
 *
 * @param {Object} props - Component props
 * @param {Array<{label: string, slug: string, disabled?: boolean, icon?: string, activeIcon?: string, iconClassName?: string}>} props.tabs - Array of tab objects
 * @param {Record<string, JSX.Element>} props.children - Object with keys matching tab slugs, values are the content to render
 * @param {string} [props.defaultTab] - Default active tab slug (defaults to first tab)
 * @param {string} [props.activeTab] - Controlled active tab
 * @param {(slug: string) => void} [props.onTabChange] - Callback when tab changes
 * @param {string} [props.className] - Additional class name
 * @param {boolean} [props.nestedGapEnd] - Add gap between nested tabs and content (default: true)
 */
export default function NestedTabs({
                                       tabs,
                                       children,
                                       defaultTab,
                                       activeTab: controlledActiveTab,
                                       onTabChange,
                                       className,
                                       urlQueryParamName,
                                       nestedGapEnd = true
                                   }) {
    const [internalActiveTab, setInternalActiveTab] = useState(defaultTab || tabs[0]?.slug);
    const tabRefs = useRef({});

    // Use controlled tab if provided, otherwise use internal state
    const activeTab = controlledActiveTab !== undefined ? controlledActiveTab : internalActiveTab;

    useEffect(() => {
        // Update internal state when controlled value changes
        if (controlledActiveTab !== undefined) {
            setInternalActiveTab(controlledActiveTab);
        }
    }, [controlledActiveTab]);

    useEffect(() => {
        if (!urlQueryParamName) {
            return;
        }
        // Update URL query parameter when active tab changes
        if (activeTab) {
            const url = new URL(window.location);
            url.searchParams.set(urlQueryParamName, activeTab);
            window.history.replaceState({}, '', url);
        }
    }, [activeTab, urlQueryParamName]);

    useEffect(() => {
        // Auto-scroll active tab button into view only if needed
        if (activeTab && tabRefs.current[activeTab]) {
            // Use setTimeout to ensure DOM is updated
            setTimeout(() => {
                const tabButton = tabRefs.current[activeTab];
                const scrollContainer = tabButton?.parentElement;

                if (!tabButton || !scrollContainer) return;

                const tabRect = tabButton.getBoundingClientRect();
                const containerRect = scrollContainer.getBoundingClientRect();

                // Check if tab is cut off on the right side
                if (tabRect.right > containerRect.right) {
                    // Scroll so tab's right edge aligns with container's right edge + 14px padding
                    const scrollAmount = tabRect.right - containerRect.right + 14;
                    scrollContainer.scrollBy({
                        left: scrollAmount,
                        behavior: 'smooth'
                    });
                }
                // Check if tab is cut off on the left side
                else if (tabRect.left < containerRect.left) {
                    // Scroll so tab's left edge aligns with container's left edge - 14px padding
                    const scrollAmount = tabRect.left - containerRect.left - 14;
                    scrollContainer.scrollBy({
                        left: scrollAmount,
                        behavior: 'smooth'
                    });
                }
                // Tab is fully visible, no scroll needed
            }, 100);
        }
    }, [activeTab]);

    const handleTabClick = (e, tab) => {
        if (e?.stopPropagation) {
            e.stopPropagation();
        }

        // Don't switch if tab is disabled
        if (tab.disabled) {
            return;
        }

        if (controlledActiveTab === undefined) {
            setInternalActiveTab(tab.slug);
        }

        if (onTabChange) {
            onTabChange(tab.slug);
        }
    };

    return <>
        <div
            className={`lbaic-settings-tab-group lbaic-settings-tab-group-nested lbaic-settings-scroll-x lbaic-settings-scroll-style lbaic-settings-divider${className ? ' ' + className : ''}`}>
            {tabs.map((tab, i) =>
                <button
                    key={i}
                    ref={(el) => (tabRefs.current[tab.slug] = el)}
                    className={`lbaic-settings-tab-nested lbaic-settings-tab${tab.slug === activeTab ? ' active' : ''}${tab.disabled ? ' lbaic-settings-button-disabled' : ''}`}
                    onClick={(e) => handleTabClick(e, tab)}
                    disabled={tab.disabled}>
                    {tab.icon && (
                        <svg
                            className={`lbaic-settings-tab-i${tab.disabled ? ' lbaic-settings-disabled' : ''}`}
                            xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24'>
                            <use href={`#lbaic-settings-tab-${tab.icon}`} className={`lbaic-settings-tab-i-default${tab.iconClassName ? ' ' + tab.iconClassName : ''}`}/>
                            <use href={`#lbaic-settings-tab-${tab.activeIcon || tab.icon}`} className='lbaic-settings-tab-i-active'/>
                        </svg>
                    )}
                    <span className='lbaic-settings-tab-label lbaic-settings-tab-nested-label'>{tab.label}</span>
                </button>
            )}
        </div>
        {nestedGapEnd && (
            <div className="lbaic-settings-divider-gap-nested-end"/>
        )}
        {/* Render all tab content to keep them mounted, show only active one */}
        {Object.entries(children || {}).map(([slug, content]) => {
            const isActive = slug === activeTab;
            return (
                <div key={slug} style={{display: isActive ? 'contents' : 'none'}}>
                    {content}
                </div>
            );
        })}
    </>
}

