import { useState, useCallback } from "react";

const useTabs = (initialTab) => {
    const [tabs, setTabs] = useState([]);
    const [activeTab, setActiveTab] = useState(initialTab);

    const handleOpenTab = useCallback((newTab) => {
        setTabs((prevTabs) => {
            const exists = prevTabs.some((tab) => tab.id === newTab.id);
            if (!exists) {
                return [...prevTabs, newTab];
            }
            return prevTabs;
        });
        setActiveTab(newTab.id);
    }, []);

    const handleCloseTab = useCallback((id) => {
        setTabs((prevTabs) => {
            const newTabs = prevTabs.filter((tab) => tab.id !== id);
            if (activeTab === id) {
                setActiveTab(newTabs.length > 0 ? newTabs[newTabs.length - 1].id : initialTab);
            }
            return newTabs;
        });
    }, [activeTab, initialTab]);

    const updateTabContent = useCallback((id, content) => {
        setTabs(prevTabs =>
            prevTabs.map(tab =>
                tab.id === id ? { ...tab, content } : tab
            )
        );
    }, []);

    return {
        tabs,
        activeTab,
        handleOpenTab,
        handleCloseTab,
        setActiveTab,
        updateTabContent
    };
};

export default useTabs;
