"use client";

import Image from "next/image";
import Link from "next/link";
import { usePathname, useSearchParams } from "next/navigation";
import { ShoppingBag, Menu, X, ChevronDown, Search, Phone, User } from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";
import { Suspense, useEffect, useRef, useState } from "react";
import { useCart } from "@/context/CartContext";
import { useStore } from "@/context/StoreContext";
import { useAuth } from "@/context/AuthContext";
import { company } from "@/data/company";

const navLinks = [
  { to: "/", label: "Home", match: (pathname: string) => pathname === "/" },
  {
    to: "/products",
    label: "Products",
    match: (pathname: string) => pathname === "/products" || pathname.startsWith("/product/"),
  },
  { to: "/cart", label: "Cart", match: (pathname: string) => pathname === "/cart" || pathname === "/checkout" },
];

function DesktopNavLink({
  href,
  label,
  active,
}: {
  href: string;
  label: string;
  active: boolean;
}) {
  return (
    <Link
      href={href}
      prefetch={false}
      className={`relative inline-flex h-10 items-center px-4 text-sm font-medium transition-colors ${
        active ? "text-white" : "text-white/70 hover:text-white"
      }`}
    >
      <span className="relative z-10">{label}</span>
      {active && (
        <motion.span
          layoutId="desktop-nav-pill"
          className="absolute inset-x-1 inset-y-1.5 rounded-md bg-white/10 ring-1 ring-white/15"
          transition={{ type: "spring", stiffness: 420, damping: 32 }}
        />
      )}
      {active && (
        <motion.span
          layoutId="desktop-nav-underline"
          className="absolute inset-x-3 bottom-0 h-[2px] rounded-full bg-primary"
          transition={{ type: "spring", stiffness: 420, damping: 32 }}
        />
      )}
    </Link>
  );
}

function NavbarInner() {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const { totalItems, openCart } = useCart();
  const { store } = useStore();
  const { user, isAdmin, logout } = useAuth();
  const [mobileOpen, setMobileOpen] = useState(false);
  const [showTopStrip, setShowTopStrip] = useState(true);
  const [categoryOpen, setCategoryOpen] = useState(false);
  const [mounted, setMounted] = useState(false);
  const categoryRef = useRef<HTMLDivElement>(null);
  const activeCategoryName = searchParams.get("category");

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setMounted(true);
  }, []);

  useEffect(() => {
    const onPointerDown = (event: MouseEvent) => {
      if (!categoryRef.current?.contains(event.target as Node)) {
        setCategoryOpen(false);
      }
    };
    document.addEventListener("mousedown", onPointerDown);
    return () => document.removeEventListener("mousedown", onPointerDown);
  }, []);

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setMobileOpen(false);
    setCategoryOpen(false);
  }, [pathname]);

  const categories = mounted ? store.categories : [];
  const cartActive = pathname === "/cart" || pathname === "/checkout";
  const adminActive = pathname.startsWith("/admin");
  const loginActive = pathname === "/login" || pathname === "/signup";
  const categoryMenuActive = pathname === "/products" && Boolean(activeCategoryName);

  return (
    <>
      <nav className="sticky top-0 z-50 border-b border-border/60 bg-background shadow-card">
        {showTopStrip && (
          <div className="bg-primary px-4 py-2 text-xs text-primary-foreground">
            <div className="container mx-auto flex items-center justify-between">
              <p className="mx-auto font-medium tracking-wide">Welcome to {company.name} — {company.tagline}</p>
              <button type="button" onClick={() => setShowTopStrip(false)} className="text-primary-foreground/80 hover:text-primary-foreground">
                close
              </button>
            </div>
          </div>
        )}

        <div className="container mx-auto flex h-[84px] items-center justify-between gap-4 px-4 lg:px-8">
          <Link href="/" prefetch={false} className="relative z-10 flex shrink-0 items-center">
            <Image
              src={company.logo}
              alt={company.name}
              width={168}
              height={48}
              className="h-11 w-auto object-contain"
              priority
            />
          </Link>

          <div className="hidden flex-1 items-center gap-2 rounded-full border border-border bg-card px-3 py-2 lg:flex">
            <div className="relative min-w-[190px]">
              <select className="w-full appearance-none rounded-full border border-border bg-background px-4 py-2 text-sm">
                <option>All Categories</option>
                {categories.map((category) => (
                  <option key={category.id}>{category.name}</option>
                ))}
              </select>
              <ChevronDown className="pointer-events-none absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            </div>
            <div className="h-6 w-px bg-border" />
            <input
              type="text"
              placeholder="Search for products..."
              className="w-full bg-transparent px-2 text-sm outline-none"
            />
            <button type="button" className="inline-flex items-center gap-2 rounded-full bg-primary px-6 py-2 text-sm font-semibold text-primary-foreground">
              <Search className="h-4 w-4" /> Search
            </button>
          </div>

          <div className="relative z-10 flex items-center gap-3">
            <Link
              href={user ? "/orders" : "/login"}
              prefetch={false}
              className={`hidden rounded-full border p-2.5 transition-all lg:block ${
                loginActive || pathname.startsWith("/orders")
                  ? "border-primary/40 bg-primary/10 text-primary"
                  : "border-border text-muted-foreground hover:text-foreground"
              }`}
              title={user ? "My Orders" : "Login"}
            >
              <User className="h-4 w-4" />
            </Link>
            <button
              type="button"
              onClick={openCart}
              className={`relative flex h-10 w-10 items-center justify-center rounded-full border transition-all ${
                cartActive
                  ? "border-primary/45 bg-primary/10 text-primary shadow-[0_0_0_3px_hsl(218_78%_43%/0.12)]"
                  : "border-border bg-card hover:border-primary/35"
              }`}
            >
              <ShoppingBag className="h-[18px] w-[18px]" />
              {totalItems > 0 && (
                <motion.span
                  initial={{ scale: 0 }}
                  animate={{ scale: 1 }}
                  className="absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-[10px] font-bold text-primary-foreground"
                >
                  {totalItems}
                </motion.span>
              )}
            </button>
            <button type="button" className="flex h-10 w-10 items-center justify-center rounded-full border border-border bg-card lg:hidden" onClick={() => setMobileOpen((v) => !v)}>
              {mobileOpen ? <X className="h-[18px] w-[18px]" /> : <Menu className="h-[18px] w-[18px]" />}
            </button>
          </div>
        </div>

        <div className="hidden bg-foreground text-white lg:block">
          <div className="container mx-auto flex h-[52px] items-center justify-between px-4 lg:px-8">
            <div className="flex items-center gap-1">
              <div className="relative" ref={categoryRef}>
                <button
                  type="button"
                  onClick={() => setCategoryOpen((open) => !open)}
                  className={`inline-flex h-10 items-center gap-2 px-4 text-sm font-semibold transition-all ${
                    categoryOpen || categoryMenuActive
                      ? "bg-primary text-primary-foreground"
                      : "hover:bg-white/10"
                  }`}
                >
                  <Menu className="h-4 w-4" />
                  SHOP BY CATEGORY
                  <ChevronDown className={`h-4 w-4 transition-transform ${categoryOpen ? "rotate-180" : ""}`} />
                </button>
                {categoryOpen && (
                  <div className="absolute left-0 top-full z-[60] mt-1 max-h-[70vh] w-72 overflow-y-auto rounded-lg border border-border bg-card p-2 shadow-elevated">
                    {categories.length === 0 ? (
                      <p className="px-3 py-2 text-sm text-muted-foreground">Loading categories…</p>
                    ) : (
                      categories.map((category) => {
                        const isCategoryActive = activeCategoryName === category.name;
                        return (
                          <Link
                            key={category.id}
                            href={`/products?category=${encodeURIComponent(category.name)}`}
                            prefetch={false}
                            onClick={() => setCategoryOpen(false)}
                            className={`block rounded-md px-3 py-2 text-sm transition-colors ${
                              isCategoryActive
                                ? "bg-primary/10 font-semibold text-primary"
                                : "text-muted-foreground hover:bg-secondary hover:text-foreground"
                            }`}
                          >
                            {category.name}
                          </Link>
                        );
                      })
                    )}
                  </div>
                )}
              </div>
              {navLinks.map((link) => (
                <DesktopNavLink
                  key={link.label}
                  href={link.to}
                  label={link.label}
                  active={link.match(pathname)}
                />
              ))}
              <DesktopNavLink
                href="/about"
                label="About Us"
                active={pathname === "/about"}
              />
              {isAdmin && (
                <DesktopNavLink href="/admin/dashboard" label="Admin" active={adminActive} />
              )}
            </div>
            <a href={company.phoneHref} className="inline-flex items-center gap-2 text-sm text-white/90 transition-colors hover:text-white">
              <Phone className="h-3.5 w-3.5" />
              {company.phone}
            </a>
          </div>
        </div>
      </nav>
      <AnimatePresence>
        {mobileOpen && (
          <motion.div
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: "auto" }}
            exit={{ opacity: 0, height: 0 }}
            className="fixed inset-x-0 top-[72px] z-40 overflow-hidden border-b border-border bg-card backdrop-blur-xl lg:hidden"
          >
            <div className="container mx-auto flex max-h-[80vh] flex-col gap-1 overflow-y-auto px-4 py-4">
              <div className="mb-2 rounded-xl border border-border bg-card p-3">
                <input type="text" placeholder="Search for products..." className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none" />
              </div>
              {navLinks.map((link) => {
                const active = link.match(pathname);
                return (
                  <Link
                    key={link.label}
                    href={link.to}
                    prefetch={false}
                    onClick={() => setMobileOpen(false)}
                    className={`relative rounded-xl px-4 py-3 text-sm font-medium transition-colors ${
                      active
                        ? "bg-primary/10 font-semibold text-primary"
                        : "text-muted-foreground hover:bg-secondary hover:text-foreground"
                    }`}
                  >
                    {active && (
                      <span className="absolute inset-y-2 left-0 w-1 rounded-r-full bg-primary" />
                    )}
                    {link.label}
                  </Link>
                );
              })}
              <Link
                href="/about"
                prefetch={false}
                onClick={() => setMobileOpen(false)}
                className={`relative rounded-xl px-4 py-3 text-sm font-medium transition-colors ${
                  pathname === "/about"
                    ? "bg-primary/10 font-semibold text-primary"
                    : "text-muted-foreground hover:bg-secondary hover:text-foreground"
                }`}
              >
                {pathname === "/about" && (
                  <span className="absolute inset-y-2 left-0 w-1 rounded-r-full bg-primary" />
                )}
                About Us
              </Link>
              <p className="px-4 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                Shop by Category
              </p>
              {categories.map((category) => {
                const isCategoryActive = activeCategoryName === category.name;
                return (
                  <Link
                    key={category.id}
                    href={`/products?category=${encodeURIComponent(category.name)}`}
                    prefetch={false}
                    onClick={() => setMobileOpen(false)}
                    className={`rounded-xl px-4 py-3 text-sm font-medium transition-colors ${
                      isCategoryActive
                        ? "bg-primary/10 font-semibold text-primary"
                        : "text-muted-foreground hover:bg-secondary hover:text-foreground"
                    }`}
                  >
                    {category.name}
                  </Link>
                );
              })}
              {isAdmin && (
                <Link
                  href="/admin/dashboard"
                  prefetch={false}
                  onClick={() => setMobileOpen(false)}
                  className={`rounded-xl px-4 py-3 text-sm font-medium transition-colors ${
                    adminActive
                      ? "bg-primary/10 font-semibold text-primary"
                      : "text-muted-foreground hover:bg-secondary hover:text-foreground"
                  }`}
                >
                  Admin Dashboard
                </Link>
              )}
              {user ? (
                <>
                  <Link
                    href="/orders"
                    prefetch={false}
                    onClick={() => setMobileOpen(false)}
                    className={`rounded-xl px-4 py-3 text-sm font-medium transition-colors ${
                      pathname.startsWith("/orders")
                        ? "bg-primary/10 font-semibold text-primary"
                        : "text-muted-foreground hover:bg-secondary hover:text-foreground"
                    }`}
                  >
                    My Orders
                  </Link>
                  <button
                    type="button"
                    onClick={() => {
                      void logout();
                      setMobileOpen(false);
                    }}
                    className="rounded-xl px-4 py-3 text-left text-sm font-medium text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
                  >
                    Logout
                  </button>
                </>
              ) : (
                <>
                  <Link
                    href="/login"
                    prefetch={false}
                    onClick={() => setMobileOpen(false)}
                    className={`rounded-xl px-4 py-3 text-sm font-medium transition-colors ${
                      pathname === "/login"
                        ? "bg-primary/10 font-semibold text-primary"
                        : "text-muted-foreground hover:bg-secondary hover:text-foreground"
                    }`}
                  >
                    Login
                  </Link>
                  <Link
                    href="/signup"
                    prefetch={false}
                    onClick={() => setMobileOpen(false)}
                    className={`rounded-xl px-4 py-3 text-sm font-medium transition-colors ${
                      pathname === "/signup"
                        ? "bg-primary/10 font-semibold text-primary"
                        : "text-muted-foreground hover:bg-secondary hover:text-foreground"
                    }`}
                  >
                    Sign Up
                  </Link>
                </>
              )}
              <a
                href={company.phoneHref}
                className="mt-2 inline-flex items-center gap-2 rounded-xl px-4 py-3 text-sm font-semibold text-primary"
              >
                <Phone className="h-4 w-4" />
                {company.phone}
              </a>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}

export default function Navbar() {
  return (
    <Suspense fallback={<div className="h-[136px] border-b border-border/60 bg-background" />}>
      <NavbarInner />
    </Suspense>
  );
}
