"use client"

import {
  BarChart,
  Clipboard,
  Home,
  Package,
  ShoppingCart,
  User,
} from "lucide-react"
import Link from "next/link"
import { usePathname } from "next/navigation"

import {
  Sidebar,
  SidebarContent,
  SidebarGroup,
  SidebarGroupContent,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
} from "@/components/ui/sidebar"

import { SidebarSection } from "./sidebar/sidebarSection"

const items = [
  {
    type: "item",
    title: "Home",
    url: "/",
    icon: Home,
  },
  {
    type: "section",
    title: "Inventory",
    url: "#",
    icon: Package,
    items: [
      {
        title: "Items",
        url: "/inventory/items",
      },
      {
        title: "Categories",
        url: "/inventory/categories",
      },
      {
        title: "Assets",
        url: "/inventory/assets",
      },
    ],
  },
  {
    type: "item",
    title: "Recipients",
    url: "/recipients",
    icon: User,
  },
  {
    type: "item",
    title: "Movements",
    url: "/movements",
    icon: BarChart,
  },
  {
    type: "item",
    title: "Assignments",
    url: "/assignments",
    icon: Clipboard,
  },
]

export default function AppSidebar({
  ...props
}: React.ComponentProps<typeof Sidebar>) {
  const pathname = usePathname()

  return (
    <Sidebar {...props}>
      <SidebarHeader className="flex items-center gap-2 p-4">
        <Link href="/" className="flex flex-col items-center gap-2">
          <ShoppingCart className="h-6 w-6" />
          <span>Stock Manager</span>
        </Link>
      </SidebarHeader>
      <SidebarContent className="flex flex-col gap-1 p-2">
        <SidebarGroup>
          <SidebarGroupContent>
            <SidebarMenu>
              {items.map((item, index) => {
                if (item.type === "item") {
                  const isActive =
                    item.url === "/"
                      ? pathname === "/"
                      : pathname.startsWith(item.url)

                  return (
                    <SidebarMenuItem key={`item-${index}`}>
                      <SidebarMenuButton asChild isActive={isActive}>
                        <Link href={item.url}>
                          <item.icon className="mr-2 h-4 w-4" />
                          <span>{item.title}</span>
                        </Link>
                      </SidebarMenuButton>
                    </SidebarMenuItem>
                  )
                }
                if (item.type === "section") {
                  return (
                    <SidebarSection
                      key={`section-${index}`}
                      title={item.title}
                      icon={item.icon}
                      items={item.items}
                    />
                  )
                }
                return null
              })}
            </SidebarMenu>
          </SidebarGroupContent>
        </SidebarGroup>
      </SidebarContent>
    </Sidebar>
  )
}
