import React, { useState, useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';

interface TabItem {
    id: string;
    label: string;
    icon?: React.ReactNode;
    path?: string; // Optional path for navigation
}

interface TabsProps {
    tabs: TabItem[];
    defaultTab?: string;
    onChange?: (tabId: string) => void;
    usePathNavigation?: boolean; // New prop to control behavior
}

const Tabs: React.FC<TabsProps> = ({ tabs, defaultTab, onChange, usePathNavigation = false }) => {
    const [activeTab, setActiveTab] = useState(defaultTab || tabs[0]?.id);
    const location = useLocation();
    const navigate = useNavigate();

    // Sync active tab with URL path if usePathNavigation is true
    useEffect(() => {
        if (usePathNavigation) {
            const currentTab = tabs.find(tab => tab.path === location.pathname);
            if (currentTab) {
                setActiveTab(currentTab.id);
            }
        }
    }, [location.pathname, tabs, usePathNavigation]);

    const handleClick = (tab: TabItem) => {
        setActiveTab(tab.id);
        onChange?.(tab.id);

        // Navigate if path exists and usePathNavigation is true
        if (usePathNavigation && tab.path) {
            navigate(tab.path);
        }
    };

    return (
        <div className="flex gap-3 bg-gray-100 p-1 rounded-xl w-fit shadow-sm">
            {tabs.map((tab) => {
                let isActive = false;

                if (usePathNavigation && tab.path) {
                    isActive = location.pathname === tab.path;
                } else {
                    isActive = activeTab === tab.id;
                }

                return (
                    <button
                        key={tab.id}
                        onClick={() => handleClick(tab)}
                        className={`
                            flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all duration-200
                            ${isActive
                                ? 'bg-white shadow text-primary'
                                : 'text-gray-500 hover:text-gray-700'}
                        `}
                    >
                        {tab.icon && <span className="text-lg">{tab.icon}</span>}
                        {tab.label}
                    </button>
                );
            })}
        </div>
    );
};

export default Tabs;
