import {useEffect, useRef, useState} from "@wordpress/element";
import {createHooks} from "@wordpress/hooks";
import ContentTabs from "../tabs";
import {NavLink, useNavigate, useSearchParams} from "react-router-dom";
import {
    getDefaultPageLayoutData,
    getNavLinkTo,
    getNavLinkToParams,
    getPageLayoutData,
    tabLinkClasses
} from "../../../../../../helpers";
import useSettings from "../../../state";
import HeaderLayout from "../header-layout";

if (!LimbChatbot?.Hooks) {
    LimbChatbot.Hooks = createHooks();
}

LimbChatbot.Hooks.addFilter('lbaic.admin.page.settings.tabLink.classes', 'lbaic/admin/page/settings/tab-link/classes', (classes, tabItem, params, state) => {
    if (tabItem?.disabled) {
        return [...classes, 'lbaic-settings-disabled'];
    }
    return classes;
});

function ContentHeader({title, subTitle}) {
    const navigate = useNavigate();
    const {navItems, pages} = useSettings();
    const [searchParams, setSearchParams] = useSearchParams();
    const [currentPage, setCurrentPage] = useState({
        menu: '',
        tab: '',
        key: '',
        layoutData: {},
    });
    const [currentTab, setCurrentTab] = useState(null);
    const tabsRefs = useRef({});

    useEffect(() => {
        const pageData = getCurrentPageState();
        setCurrentPage(pageData);
        // Check page existence
        if (!(pageData.key in pages)) {
            // Get default page data
            const data = getDefaultPageLayoutData(navItems, pageData.menu);
            if (data) {
                // Redirection page route info
                const menu = data.slug;
                const tab = data.tabs?.length ? data.tabs[0].slug || '' : '';
                // Navigate to the right page
                navigate(getNavLinkTo(menu, tab));
            }
        } else {
            setTimeout(() => {
                // Current tab position
                if (pageData.tab in tabsRefs.current && tabsRefs.current[pageData.tab]) {
                    setCurrentTab(tabsRefs.current[pageData.tab].getBoundingClientRect());
                } else {
                    setCurrentTab(null);
                }
            }, 400);
        }
    }, [searchParams]);

    const getCurrentPageState = () => {
        const menu = searchParams.get('menu');
        const tab = searchParams.get('tab');
        const key = getNavLinkToParams(menu, tab, true);
        const layoutData = getPageLayoutData(navItems, menu) || {};

        return {menu, tab, key, layoutData};
    }

    return (
        <HeaderLayout
            title={title}
            subTitle={subTitle}
        >
            {currentPage.layoutData?.tabs?.length > 0 && (
                <ContentTabs currentTab={currentTab}>
                    {!!currentPage.layoutData.tabs?.length && (
                        currentPage.layoutData.tabs.map(tab => (
                            tab.disabled ? (
                                <span
                                    key={tab.slug}
                                    ref={(el) => (tabsRefs.current[tab.slug] = el)}
                                    className={tabLinkClasses(tab, getNavLinkToParams(currentPage.menu, tab.slug), {})}
                                    onClick={(e) => e.preventDefault()}
                                    role="button"
                                    aria-disabled="true"
                                >
                                    {tab.icon}
                                    <span className="lbaic-settings-tab-label">{tab.label}</span>
                                    {tab.badge}
                                </span>
                            ) : (
                                <NavLink
                                    key={tab.slug}
                                    ref={(el) => (tabsRefs.current[tab.slug] = el)}
                                    to={getNavLinkTo(currentPage.menu, tab.slug)}
                                    className={(state) => tabLinkClasses(tab, getNavLinkToParams(currentPage.menu, tab.slug), state)}
                                >
                                    {tab.icon}
                                    <span className="lbaic-settings-tab-label">{tab.label}</span>
                                    {tab.badge}
                                </NavLink>
                            )
                        ))
                    )}
                </ContentTabs>
            )}
        </HeaderLayout>
    );
}

export default ContentHeader;