import React, { useContext, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { setSelectedTab } from '../../store/navigationSlice';
import { FolderTree, LayoutTemplate } from "lucide-react";
import TreeTab from "./SideTabs/TreeTab";
import TemplateTab from "./SideTabs/TemplateTab";
import { AuthContext } from "../../AuthProvider";
import { ScrollArea } from "../ui/scroll-area";
import { cn } from "../../lib/utils";

const SideNavigation = () => {
    const { roles } = useContext(AuthContext);
    const selectedTab = useSelector(state => state.navigation.selectedTab);
    const dispatch = useDispatch();

    const allTabs = [
        { id: "tree", label: "Tree", icon: FolderTree, component: <TreeTab /> },
        { id: "templates", label: "Templates", icon: LayoutTemplate, component: <TemplateTab /> },
    ];

    const visibleTabs = roles.includes("admin")
        ? allTabs
        : allTabs.filter(tab => tab.id === "tree");

    useEffect(() => {
        if (!visibleTabs.find(tab => tab.id === selectedTab)) {
            dispatch(setSelectedTab(visibleTabs[0]?.id || ""));
        }
    }, [visibleTabs, selectedTab, dispatch]);

    const current = visibleTabs.find(t => t.id === selectedTab);

    return (
        <aside className="flex w-72 shrink-0 flex-col border-r border-border bg-surface/40">
            <div className="flex items-center gap-1 border-b border-border p-2">
                {visibleTabs.map(tab => {
                    const Icon = tab.icon;
                    const active = tab.id === selectedTab;
                    return (
                        <button
                            key={tab.id}
                            type="button"
                            onClick={() => dispatch(setSelectedTab(tab.id))}
                            className={cn(
                                "inline-flex flex-1 items-center justify-center gap-1.5 rounded-md px-3 py-1.5 font-mono text-xs font-medium uppercase tracking-wide transition-all",
                                active
                                    ? "bg-primary/15 text-primary shadow-[0_0_12px_-4px_hsl(var(--primary)/0.6)]"
                                    : "text-muted-foreground hover:bg-accent hover:text-foreground"
                            )}
                        >
                            <Icon className="h-3.5 w-3.5" />
                            {tab.label}
                        </button>
                    );
                })}
            </div>
            <ScrollArea className="flex-1">
                <div className="p-3">{current?.component}</div>
            </ScrollArea>
        </aside>
    );
};

export default SideNavigation;
