import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import React, { createContext, useCallback, useEffect, useState, } from 'react';
import { matchPath, Outlet, Route, Routes, useLocation, useNavigate, } from 'react-router';
import styled from 'styled-components';
import { ButtonIcon } from '../buttonv2/Buttonv2.component';
import { BasicText, EmphaseText, SecondaryText } from '../text/Text.component';
import { ScrollButton } from './ScrollButton';
import { ScrollableContainer, TabBar, TabContent, TabItem, TabsContainer, TabsScroller, } from './StyledTabs';
import { Tab } from './Tab';
import { useScrollingTabs } from './useScrollingTabs';
export const TabsContext = createContext(false);
const TabIcon = styled(ButtonIcon) `
  color: ${(props) => props.theme.textSecondary};
`;
function Tabs({ activeTabColor, activeTabSeparator, tabLineColor, inactiveTabColor, tabContentColor, separatorColor, tabHoverColor, children, className, ...rest }) {
    const location = useLocation();
    const navigate = useNavigate();
    const url = location.pathname;
    const [selectedTabIndex, setSelectedTabIndex] = useState(null);
    const queryURL = new URLSearchParams(location.search);
    const filteredTabsChildren = React.Children.toArray(children).filter((child) => React.isValidElement(child) && child.type === Tab);
    const matchQuery = useCallback((query) => {
        for (const key of Object.keys(query)) {
            // To support the case of {tab:null}
            if (queryURL.get(key) === null && !query[key]) {
                return true;
            }
            if (!(queryURL.has(key) && queryURL.get(key) === query[key]))
                return false;
        }
        return true;
    }, [queryURL]);
    const serialize = (query) => {
        if (!query) {
            return '';
        }
        else {
            const o = Object.fromEntries(Object.entries(query).filter(([_, v]) => v != null));
            //$FlowFixMe
            return '?' + new URLSearchParams(o).toString();
        }
    };
    const getPushHistoryPath = (path, query) => {
        const sanitizedSegment = path.replace(/^\/+/, '');
        const replaceUrl = location.pathname.replace(/[^/]+$/, sanitizedSegment);
        if (path.startsWith('/')) {
            return `${replaceUrl}${serialize(query)}`;
        }
        return `${path}${serialize(query)}`;
    };
    useEffect(() => {
        let hasSelectedTab = false;
        filteredTabsChildren.forEach((child, index) => {
            const isSelected = !!matchPath((child.props.path.startsWith('/')
                ? child.props.path
                : url + '/' + child.props.path) + '*', location.pathname) && (child.props.query ? matchQuery(child.props.query) : true);
            if (isSelected) {
                setSelectedTabIndex(index);
                hasSelectedTab = true;
            }
        });
        if (!hasSelectedTab)
            setSelectedTabIndex(null);
    }, [location.pathname, filteredTabsChildren, matchQuery]);
    const { scrollButtonEndRef, scrollButtonStartRef, tabsListRef, tabsRef, handleStartScrollClick, handleEndScrollClick, handleTabsScroll, handleKeyDown, displayScroll, } = useScrollingTabs(selectedTabIndex);
    const tabItems = filteredTabsChildren.map((child, index) => {
        const { path, query, label, textBadge, children, icon, ...childRest } = child.props;
        const isSelected = selectedTabIndex === index;
        const realPath = path.startsWith('/') ? `/${path.split('/').pop()}` : path;
        return (_jsxs(TabItem, { className: `sc-tabs-item ${isSelected ? 'selected' : ''}`, role: "tab", onClick: () => navigate(getPushHistoryPath(realPath, query)), selected: isSelected, tabHoverColor: tabHoverColor, inactiveTabColor: inactiveTabColor, activeTabColor: activeTabColor, activeTabSeparator: activeTabSeparator, tabIndex: isSelected ? 0 : -1, onKeyDown: (event) => {
                if (event.key === ' ' ||
                    event.key === 'Enter' ||
                    event.key === 'Spacebar') {
                    event.preventDefault();
                    navigate(getPushHistoryPath(realPath, query));
                }
            }, ...childRest, children: [icon && _jsx(TabIcon, { label: label, children: icon }), isSelected ? (_jsx(BasicText, { children: label })) : (_jsx(SecondaryText, { children: label })), textBadge && _jsx(EmphaseText, { children: textBadge })] }, index));
    });
    return (_jsx(TabsContext.Provider, { value: true, children: _jsxs(TabsContainer, { style: { containerType: 'size' }, className: ['sc-tabs', className].join(' '), tabLineColor: tabLineColor, separatorColor: separatorColor, ...rest, children: [_jsxs(ScrollableContainer, { children: [displayScroll.start && (_jsx(ScrollButton, { ref: scrollButtonStartRef, direction: "left", onClick: handleStartScrollClick })), _jsx(TabsScroller, { ref: tabsRef, onScroll: handleTabsScroll, children: _jsx(TabBar, { onKeyDown: handleKeyDown, ref: tabsListRef, className: "sc-tabs-bar", role: "tablist", children: tabItems }) }), displayScroll.end && (_jsx(ScrollButton, { ref: scrollButtonEndRef, direction: "right", onClick: handleEndScrollClick }))] }), _jsx(Routes, { children: filteredTabsChildren.map((tab, index) => {
                        const path = tab.props.path.split('/').pop();
                        if (tab.props.query && !matchQuery(tab.props.query)) {
                            return _jsx(_Fragment, {});
                        }
                        return (_jsx(Route, { path: tab.props.path.startsWith('/') ? '/' + path : path, element: _jsxs(_Fragment, { children: [_jsx(TabContent, { className: "sc-tabs-item-content", tabContentColor: tabContentColor, withoutPadding: tab.props.withoutPadding, children: tab.props.children }), _jsx(Outlet, {})] }) }, index));
                    }) })] }) }));
}
Tabs.Tab = Tab;
// re-export Tab
export { Tab, Tabs };
