"use client";

import Image from "next/image";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useState } from "react";
import { CategoriesIcon, ChevronDownIcon, DashboardIcon, OffersIcon, ProductsCameraIcon } from "./icons";

const navItems = [
  { key: "dashboard", label: "Dashboard", href: "/dashboard", icon: DashboardIcon },
  {
    key: "sellers",
    label: "Sellers",
    href: "/sellers",
    image: "/assets/sellers-nav.png",
    activeImage: "/assets/sellers-nav-filled.png",
  },
  {
    key: "products",
    label: "Products",
    href: "/products",
    icon: ProductsCameraIcon,
    children: [
      { label: "New Products", href: "/products/new" },
      { label: "Used Products", href: "/products/used" },
    ],
  },
  { key: "categories", label: "Categories", href: "/categories", icon: CategoriesIcon },
  {
    key: "quotes",
    label: "Request a Quote",
    href: "/quotes",
    image: "/assets/requestaquote-nav.png",
    activeImage: "/assets/requestaquote-nav-filled.png",
  },
  { key: "offers", label: "Offers", href: "/offers", icon: OffersIcon },
  {
    key: "questions",
    label: "Questions",
    href: "/questions",
    image: "/assets/questions-nav.png",
    activeImage: "/assets/questions-nav-filled.png",
  },
];

export default function Sidebar() {
  const pathname = usePathname();
  const isProductsRoute = pathname.startsWith("/products");
  const [productsManuallyOpen, setProductsManuallyOpen] = useState<boolean | null>(null);
  const productsOpen = productsManuallyOpen ?? isProductsRoute;

  return (
    <aside className="sticky top-0 flex h-screen w-[240px] shrink-0 flex-col overflow-y-auto border-r border-[#E4E7EC] bg-[#F4F8FF]">
      <div className="flex h-20 items-center px-5">
        <Image src="/assets/av-logo.png" alt="BroadcastAV" width={170} height={31} priority />
      </div>

      <nav className="flex-1 space-y-1 px-3">
        {navItems.map((item) => {
          const isActive =
            pathname === item.href ||
            (item.href !== "/dashboard" && pathname.startsWith(`${item.href}/`)) ||
            (item.children && item.children.some((child) => pathname === child.href || pathname.startsWith(`${child.href}/`)));
          const Icon = "icon" in item ? item.icon : undefined;
          const activeImage = "activeImage" in item ? item.activeImage : undefined;
          const iconEl = Icon ? (
            <Icon active={isActive} />
          ) : isActive && activeImage ? (
            <Image src={activeImage} alt="" width={18} height={18} />
          ) : (
            <Image
              src={item.image!}
              alt=""
              width={18}
              height={18}
              className={isActive ? "brightness-0 invert" : ""}
            />
          );

          if (item.children) {
            return (
              <div key={item.key}>
                <button
                  type="button"
                  onClick={() => setProductsManuallyOpen(!productsOpen)}
                  className={`flex w-full items-center justify-between rounded-lg px-3 py-2.5 text-[13px] font-medium transition-colors ${
                    isActive ? "bg-[#1657D9] text-white" : "text-[#344054] hover:bg-[#EAF1FF] hover:text-[#1657D9]"
                  }`}
                >
                  <span className="flex items-center gap-3">
                    <item.icon className="h-4 w-4" />
                    {item.label}
                  </span>
                  <ChevronDownIcon className={`h-4 w-4 transition-transform duration-200 ${productsOpen ? "rotate-180" : ""}`} />
                </button>
                {productsOpen && (
                  <div className="mt-1.5 space-y-1.5">
                    {item.children.map((child) => {
                      const isChildActive = pathname === child.href || pathname.startsWith(`${child.href}/`);
                      return (
                        <Link
                          key={child.href}
                          href={child.href}
                          className={`flex items-center gap-2.5 rounded-lg py-2 pl-8 pr-3 text-[13px] font-medium transition-colors ${
                            isChildActive
                              ? "bg-[#1657D9] text-white"
                              : "text-[#344054] hover:text-[#1657D9]"
                          }`}
                        >
                          <Image
                            src={isChildActive ? "/assets/bookmark-nav-filled.png" : "/assets/bookmark-nav.png"}
                            alt=""
                            width={18}
                            height={18}
                          />
                          {child.label}
                        </Link>
                      );
                    })}
                  </div>
                )}
              </div>
            );
          }

          return (
            <Link
              key={item.key}
              href={item.href}
              className={`flex items-center gap-3 rounded-lg px-3 py-2.5 text-[14px] transition-colors ${
                isActive ? "bg-[#1657D9] text-white" : "text-[#344054] hover:bg-white"
              }`}
            >
              {iconEl}
              {item.label}
            </Link>
          );
        })}
      </nav>
    </aside>
  );
}
