import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
// @ts-nocheck
import React, { createContext, useEffect, useState, useCallback } from 'react';
import { TabBar, ScrollableContainer, TabContent, TabItem, TabsContainer, TabsScroller, } from './StyledTabs';
import { useHistory, useLocation, useRouteMatch, matchPath, Route, } from 'react-router-dom';
import { SecondaryText, BasicText, EmphaseText } from '../text/Text.component';
import { ScrollButton } from './ScrollButton';
import { Tab } from './Tab';
import { useScrollingTabs } from './useScrollingTabs';
import { ButtonIcon } from '../buttonv2/Buttonv2.component';
import styled from 'styled-components';
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 history = useHistory();
    const { url } = useRouteMatch();
    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) => {
        if (path.startsWith('/')) {
            return `${path}${serialize(query)}`;
        }
        return `${url}/${path}${serialize(query)}`;
    };
    useEffect(() => {
        let hasSelectedTab = false;
        filteredTabsChildren.forEach((child, index) => {
            const isSelected = !!matchPath(location.pathname, {
                path: child.props.path.startsWith('/')
                    ? child.props.path
                    : url + '/' + child.props.path,
                exact: child.props.exact,
                strict: child.props.strict,
                sensitive: child.props.sensitive,
            }) && (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;
        return (_jsxs(TabItem, { className: `sc-tabs-item ${isSelected ? 'selected' : ''}`, role: "tab", onClick: () => history.push(getPushHistoryPath(path, 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();
                    history.push(getPushHistoryPath(path, query));
                }
            }, ...childRest, children: [icon && _jsx(TabIcon, { label: label, children: icon }), isSelected ? (_jsx(BasicText, { className: "sc-tabs-item-title", children: label })) : (_jsx(SecondaryText, { className: "sc-tabs-item-title", children: label })), textBadge && (_jsx(EmphaseText, { className: "sc-tabs-item-icon", children: textBadge }))] }, index));
    });
    return (_jsx(TabsContext.Provider, { value: true, children: _jsxs(TabsContainer, { 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(TabContent, { className: "sc-tabs-item-content", tabContentColor: tabContentColor, children: filteredTabsChildren.map((tab, index) => (_jsx(Route, { exact: tab.props.exact, sensitive: tab.props.sensitive, strict: tab.props.strict, path: tab.props.path.startsWith('/')
                            ? tab.props.path
                            : url + '/' + tab.props.path, children: !tab.props.query ||
                            (tab.props.query && matchQuery(tab.props.query)) ? (tab.props.children) : (_jsx(_Fragment, {})) }, index))) })] }) }));
}
Tabs.Tab = Tab;
// re-export Tab
export { Tabs, Tab };
