import {
  Home,
  Package,
  BarChart2,
  Settings,
  ClipboardList,
  LogOut,
  Tags,
  PackagePlus,
  ShoppingBag,
  Truck,
  MessageCircle,
  LayoutDashboard,
} from "lucide-react";
import { IconCrystalBall } from "@tabler/icons-react";
import {
  Sidebar,
  SidebarContent,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarFooter,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarSeparator,
  useSidebar
} from "@/components/ui/sidebar";
import { useLocation, useNavigate, Link } from "react-router-dom";
import { Protected } from "@/components/auth/Protected";
import { useContext } from "react";
import { AuthContext } from "@/contexts/AuthContext";

const dashboardItems = [
  {
    title: "Dashboard",
    icon: LayoutDashboard,
    url: "/dashboard",
    permission: "access:dashboard"
  }
];

const inventoryItems = [
  {
    title: "Overview",
    icon: Home,
    url: "/",
    permission: "access:overview"
  },
  {
    title: "Products",
    icon: Package,
    url: "/products",
    permission: "access:products"
  },
  {
    title: "Categories",
    icon: Tags,
    url: "/categories",
    permission: "access:categories"
  },
  {
    title: "Brands",
    icon: ShoppingBag,
    url: "/brands",
    permission: "access:brands"
  },
  {
    title: "Vendors",
    icon: Truck,
    url: "/vendors",
    permission: "access:vendors"
  },
  {
    title: "Purchase Orders",
    icon: ClipboardList,
    url: "/purchase-orders",
    permission: "access:purchase_orders"
  },
  {
    title: "Analytics",
    icon: BarChart2,
    url: "/analytics",
    permission: "access:analytics"
  },
  {
    title: "Forecasting",
    icon: IconCrystalBall,
    url: "/forecasting",
    permission: "access:forecasting"
  }
];

const productSetupItems = [
  {
    title: "Create Products",
    icon: PackagePlus,
    url: "/import",
    permission: "access:import"
  }
];

const chatItems = [
  {
    title: "Chat Archive",
    icon: MessageCircle,
    url: "/chat",
    permission: "access:chat"
  }
];

export function AppSidebar() {
  const location = useLocation();
  const navigate = useNavigate();
  useSidebar();
  const { user } = useContext(AuthContext);

  const handleLogout = () => {
    localStorage.removeItem('token');
    sessionStorage.removeItem('isLoggedIn');
    navigate('/login');
  };

  // Check if user has access to any items in a section
  const hasAccessToSection = (items: typeof inventoryItems): boolean => {
    if (user?.is_admin) return true;
    return items.some(item => user?.permissions?.includes(item.permission));
  };

  const renderMenuItems = (items: typeof inventoryItems) => {
    return items.map((item) => {
      const isActive =
        location.pathname === item.url ||
        (item.url !== "/" && item.url !== "#" && location.pathname.startsWith(item.url));
      return (
        <Protected
          key={item.title}
          permission={item.permission}
          fallback={null}
        >
          <SidebarMenuItem>
            <SidebarMenuButton
              asChild={item.url !== "#"}
              tooltip={item.title}
              isActive={isActive}
              disabled={item.url === "#"}
            >
              {item.url === "#" ? (
                <div>
                  <item.icon className="h-4 w-4" />
                  <span className="group-data-[collapsible=icon]:hidden">
                    {item.title}
                  </span>
                </div>
              ) : (
                <Link to={item.url}>
                  <item.icon className="h-4 w-4" />
                  <span className="group-data-[collapsible=icon]:hidden">
                    {item.title}
                  </span>
                </Link>
              )}
            </SidebarMenuButton>
          </SidebarMenuItem>
        </Protected>
      );
    });
  };

  return (
    <Sidebar collapsible="icon" variant="sidebar">
      <SidebarHeader>
        <div className="py-1 flex justify-center items-center">
          <div className="flex items-center">
            <div className="flex-shrink-0 w-8 h-8 relative flex items-center justify-center">
              <img 
                src="/cherrybottom.png" 
                alt="Cherry Bottom" 
                className="w-6 h-6 object-contain -rotate-12 transform hover:rotate-0 transition-transform ease-in-out duration-300"
              />
            </div>
            <div className="ml-1 transition-all duration-200 whitespace-nowrap group-[.group[data-state=collapsed]]:hidden">
              <span className="font-bold text-lg">A Cherry On Bottom</span>
            </div>
          </div>
        </div>
      </SidebarHeader>
      <SidebarSeparator />
      <SidebarContent>
        {/* Dashboard Section */}
        {hasAccessToSection(dashboardItems) && (
          <SidebarGroup>
            <SidebarGroupLabel>Dashboard</SidebarGroupLabel>
            <SidebarGroupContent>
              <SidebarMenu>
                {renderMenuItems(dashboardItems)}
              </SidebarMenu>
            </SidebarGroupContent>
          </SidebarGroup>
        )}

        {/* Inventory Section */}
        {hasAccessToSection(inventoryItems) && (
          <SidebarGroup>
            <SidebarGroupLabel>Inventory</SidebarGroupLabel>
            <SidebarGroupContent>
              <SidebarMenu>
                {renderMenuItems(inventoryItems)}
              </SidebarMenu>
            </SidebarGroupContent>
          </SidebarGroup>
        )}

        {/* Product Setup Section */}
        {hasAccessToSection(productSetupItems) && (
          <SidebarGroup>
            <SidebarGroupLabel>Product Setup</SidebarGroupLabel>
            <SidebarGroupContent>
              <SidebarMenu>
                {renderMenuItems(productSetupItems)}
              </SidebarMenu>
            </SidebarGroupContent>
          </SidebarGroup>
        )}

        {/* Chat Section */}
        {hasAccessToSection(chatItems) && (
          <SidebarGroup>
            <SidebarGroupLabel>Chat</SidebarGroupLabel>
            <SidebarGroupContent>
              <SidebarMenu>
                {renderMenuItems(chatItems)}
              </SidebarMenu>
            </SidebarGroupContent>
          </SidebarGroup>
        )}

        {/* Settings Section */}
        <Protected permission="access:settings" fallback={null}>
          <SidebarGroup>
            <SidebarGroupContent>
              <SidebarMenu>
                <SidebarMenuItem>
                  <SidebarMenuButton
                    asChild
                    tooltip="Settings"
                    isActive={location.pathname === "/settings"}
                  >
                    <Link to="/settings">
                      <Settings className="h-4 w-4" />
                      <span className="group-data-[collapsible=icon]:hidden">
                        Settings
                      </span>
                    </Link>
                  </SidebarMenuButton>
                </SidebarMenuItem>
              </SidebarMenu>
            </SidebarGroupContent>
          </SidebarGroup>
        </Protected>
      </SidebarContent>
      <SidebarSeparator />
      <SidebarFooter>
        <SidebarMenu>
          <SidebarMenuItem>
            <SidebarMenuButton asChild tooltip="Logout" onClick={handleLogout}>
              <button>
                <LogOut className="h-4 w-4" />
                <span className="group-data-[collapsible=icon]:hidden">Logout</span>
              </button>
            </SidebarMenuButton>
          </SidebarMenuItem>
        </SidebarMenu>
      </SidebarFooter>
    </Sidebar>
  );
}
