import { Box, Tabs } from '@bigcommerce/big-design';
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';

export const TabIds = {
    HOSE_PARTS: 'hose_parts',
    HOSE_ASSEMBLY: 'hose_assembly',
    HOSE_REQUESTS: 'hose_requests',
    HOSE_NOTIFICATIONS: 'hose_notifications',
};

export const TabRoutes = {
    [TabIds.HOSE_PARTS]: '/hose/parts',
    [TabIds.HOSE_ASSEMBLY]: '/hose/assembly',
    [TabIds.HOSE_REQUESTS]: '/hose/requests',
    [TabIds.HOSE_NOTIFICATIONS]: '/hose/notifications',
};

const HeaderlessRoutes = [
    '/orders/[orderId]',
    '/orders/[orderId]/labels',
    '/orders/[orderId]/modal',
    '/productAppExtension/[productId]',
];

const HeaderTypes = {
    GLOBAL: 'global',
    HEADERLESS: 'headerless',
};

const Header = () => {
    const [activeTab, setActiveTab] = useState<string>('');
    const [headerType, setHeaderType] = useState<string>(HeaderTypes.GLOBAL);
    const router = useRouter();
    const { pathname } = router;

    useEffect(() => {
        if (HeaderlessRoutes.includes(pathname)) {
            setHeaderType(HeaderTypes.HEADERLESS);
        } else {
            // Check if new route matches TabRoutes
            const tabKey = Object.keys(TabRoutes).find(key => TabRoutes[key] === pathname);

            // Set the active tab to tabKey or set no active tab if route doesn't match (404)
            setActiveTab(tabKey ?? '');
            setHeaderType(HeaderTypes.GLOBAL);
        }

    }, [pathname]);

    useEffect(() => {
        router.prefetch('/hose/parts');
        router.prefetch('/hose/assembly');
        router.prefetch('/hose/requests');
        router.prefetch('/hose/notifications');
    }, [router]);

    const items = [
        { ariaControls: 'hose_parts', id: TabIds.HOSE_PARTS, title: 'Hose Parts' },
        { ariaControls: 'hose_assembly', id: TabIds.HOSE_ASSEMBLY, title: 'Hose Assembly' },
        { ariaControls: 'hose_requests', id: TabIds.HOSE_REQUESTS, title: 'Hose Requests' },
        { ariaControls: 'hose_notifications', id: TabIds.HOSE_NOTIFICATIONS, title: 'Notifications' },
    ];

    const handleTabClick = (tabId: string) => {
        setActiveTab(tabId);

        return router.push(TabRoutes[tabId]);
    };

    if (headerType === HeaderTypes.HEADERLESS) return null;

    return (
        <Box marginBottom="xxLarge">
            <Tabs
                activeTab={activeTab}
                items={items}
                onTabClick={handleTabClick}
            />
        </Box>
    );
};

export default Header;
