import { Tab, TabList, TabPanel, TabPanels, Tabs, TabsSkeleton, } from "@carbon/react";
import React from "react";
const TabPanelStyles = { paddingLeft: 0, paddingRight: 0 };
export const C3Tabs = ({ tabs, desiredTabId, onTabChange, loading = false, }) => {
    const initializedTabs = React.useRef([]);
    const visibleTabs = tabs.filter((tab) => tab.visible === undefined || tab.visible);
    visibleTabs.forEach((tab) => {
        if (tab.initializeTab && !initializedTabs.current.includes(tab.id)) {
            initializedTabs.current = [...initializedTabs.current, tab.id];
            tab.initializeTab();
        }
    });
    const foundTab = desiredTabId
        ? visibleTabs.findIndex((tab) => tab.id === desiredTabId)
        : -1;
    const selectedTab = foundTab === -1 ? 0 : foundTab;
    const [activeTabIndex, setActiveTabIndex] = React.useState(selectedTab);
    React.useEffect(() => {
        setActiveTabIndex(selectedTab);
    }, [selectedTab]);
    if (loading) {
        return React.createElement(TabsSkeleton, { key: "tabs-skeleton" });
    }
    return (React.createElement(Tabs, { selectedIndex: activeTabIndex, onChange: (event) => {
            setActiveTabIndex(event.selectedIndex);
            const newDesiredTab = visibleTabs[event.selectedIndex].id;
            if (event.selectedIndex !== activeTabIndex && onTabChange) {
                onTabChange(newDesiredTab);
            }
        } },
        React.createElement(TabList, { "aria-label": "tabs" }, visibleTabs.map((tab) => (React.createElement(Tab, { key: `${tab.id}-label` }, tab.label)))),
        React.createElement(TabPanels, null, visibleTabs.map((tab) => (React.createElement(TabPanel, { key: tab.id, style: TabPanelStyles }, tab.content))))));
};
