"use client";

import Image from "next/image";
import { useEffect, useState, useRef } from "react";
import { Package, ShoppingBag, Menu, X, LogOut, User, Search } from "lucide-react";
import { Button } from "../ui/button";
import { usePathname, useRouter } from "next/navigation";
import Link from "next/link";
import { getClientProfileAction, logoutAction } from "@/actions/auth.actions";
import { toast } from "sonner";
import { useSiteConfig } from "@/context/SiteConfigContext";
import SearchModal from "./SearchModal";

const navLinks = [
  { label: "Home", href: "#home", id: "home" },
  { label: "Products", href: "#products", id: "products" },
  { label: "Contact", href: "#contact", id: "contact" },
];

export default function Navbar() {
  const [open, setOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const siteConfig = useSiteConfig();
  const [active, setActive] = useState("home");
  const [shrink, setShrink] = useState(false);
  const [user, setUser] = useState<{ name: string; image?: string } | null>(null);
  const [loading, setLoading] = useState(true);
  const [mounted, setMounted] = useState(false);
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const [mobileDropdownOpen, setMobileDropdownOpen] = useState(false);
  const isClickScrolling = useRef(false);
  const pathname = usePathname();
  const router = useRouter();
  const isHome = pathname === "/";

  const handleNavClick = (id: string, e: React.MouseEvent<HTMLAnchorElement>) => {
    if (!isHome) {
      setOpen(false);
      return;
    }
    e.preventDefault();
    const element = document.getElementById(id);
    if (element) {
      if ((window as any).lenis) {
        (window as any).lenis.scrollTo(element, { duration: 1.2 });
      } else {
        element.scrollIntoView({ behavior: "smooth" });
      }
    }
    isClickScrolling.current = true;
    setActive(id);
    setOpen(false);
    setTimeout(() => {
      isClickScrolling.current = false;
    }, 1000);
  };

  useEffect(() => {
    const mountTimeout = setTimeout(() => {
      setMounted(true);
      if (typeof window !== "undefined") {
        try {
          const cached = localStorage.getItem("cachedUser");
          if (cached) {
            setUser(JSON.parse(cached));
            setLoading(false);
          }
        } catch { }
      }
    }, 0);

    const hasToken = typeof window !== "undefined" && document.cookie.includes("clientLoggedIn=true");
    if (!hasToken) {
      const loadTimeout = setTimeout(() => {
        setLoading(false);
      }, 0);
      return () => {
        clearTimeout(mountTimeout);
        clearTimeout(loadTimeout);
      };
    }

    const checkAuth = async () => {
      const res = await getClientProfileAction();
      if (res.success && res.data) {
        setUser(res.data);
        try {
          localStorage.setItem("cachedUser", JSON.stringify(res.data));
        } catch { }
      } else {
        setUser(null);
        try {
          localStorage.removeItem("cachedUser");
        } catch { }
      }
      setLoading(false);
    };
    checkAuth();

    window.addEventListener("profileUpdated", checkAuth);
    return () => {
      clearTimeout(mountTimeout);
      window.removeEventListener("profileUpdated", checkAuth);
    };
  }, [pathname]);

  // Support smooth scroll-to-hash when navigating from another page
  useEffect(() => {
    if (typeof window === "undefined" || !isHome) return;
    const hash = window.location.hash;
    if (hash) {
      const id = hash.replace("#", "");
      const timer = setTimeout(() => {
        const element = document.getElementById(id);
        if (element) {
          element.scrollIntoView({ behavior: "smooth" });
          setActive(id);
        }
      }, 500); // Allow time for Suspense skeletons to mount
      return () => clearTimeout(timer);
    }
  }, [pathname, isHome]);

  const handleLogout = async () => {
    const toastId = toast.loading("Logging out...");
    const res = await logoutAction();
    toast.dismiss(toastId);
    if (res.success) {
      toast.success("Logged out successfully");
      setUser(null);
      try {
        localStorage.removeItem("cachedUser");
      } catch { }
      router.push("/login");
      router.refresh();
    } else {
      toast.error("Logout failed");
    }
  };

  useEffect(() => {
    const threshold = 100;

    const onScroll = () => {
      setShrink(window.scrollY > 40 || window.innerWidth < 1280);

      if (!isHome) return;

      if (isClickScrolling.current) return;

      const isAtBottom = window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 30;
      if (isAtBottom) {
        setActive("contact");
        return;
      }

      let current = "home";
      for (const link of navLinks) {
        const el = document.getElementById(link.id);
        if (!el) continue;

        const rect = el.getBoundingClientRect();
        if (rect.top <= threshold) {
          current = link.id;
        }
      }
      setActive(current);
    };

    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, [isHome]);

  // Keyboard shortcut listener for search modal
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if ((e.ctrlKey || e.metaKey) && e.key === "k") {
        e.preventDefault();
        setSearchOpen(true);
      } else if (e.key === "/") {
        const activeEl = document.activeElement;
        if (activeEl && (activeEl.tagName === "INPUT" || activeEl.tagName === "TEXTAREA")) {
          return;
        }
        e.preventDefault();
        setSearchOpen(true);
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, []);

  return (
    <>
      <nav
        className={`fixed top-0 left-0 right-0 z-50 transition-all backdrop-blur-xl border-b border-white/10 bg-brand-surface/95
      ${shrink
            ? "h-14 shadow-xl"
            : "h-16 xl:h-20 shadow-md"
          }`}
      >
        <div className="container mx-auto px-4 h-full flex items-center justify-between">
          {/* Logo */}
          <Link
            href="/"
            className="flex items-center gap-2 text-xl lg:text-2xl font-black text-white uppercase tracking-wider transition-colors hover:text-brand-accent-light"
          >
            {siteConfig.company_logo ? (
              <Image
                src={siteConfig.company_logo}
                alt={siteConfig.company_name || "Electronics Store"}
                width={80}
                height={80}
                style={{ height: "auto" }}
                className={`object-contain transition-all duration-300 w-auto ${shrink ? "max-h-12" : "max-h-14 xl:max-h-16"
                  }`}
              />
            ) : null}
            {/* <div className="flex flex-col items-center">
            <span className="text-[10px] tracking-[0.2em] text-zinc-400 font-extrabold normal-case">
              {siteConfig.company_name || "Electronics Store"}
            </span>
          </div> */}
          </Link>

          {/* Desktop */}
          <div className="hidden xl:flex items-center gap-6">
            {navLinks.map((l) => (
              <Link
                key={l.id}
                href={isHome ? l.href : `/${l.href}`}
                onClick={(e) => handleNavClick(l.id, e)}
                className={`text-xs font-bold hover:font-black uppercase tracking-widest transition-all duration-300 ease-out
                ${active === l.id && isHome
                    ? "text-brand-accent underline underline-offset-4 decoration-2 font-black"
                    : "text-brand-text-light hover:text-brand-accent"
                  }`}
              >
                {l.label}
              </Link>
            ))}

            {mounted && user && (
              <Link
                href="/my-orders"
                className={`text-xs font-bold hover:font-black uppercase tracking-widest transition-all duration-300 ease-out
                ${pathname.startsWith("/my-orders")
                    ? "text-brand-accent underline underline-offset-4 decoration-2 font-black"
                    : "text-brand-text-light hover:text-brand-accent"
                  }`}
              >
                My Orders
              </Link>
            )}



            <Link
              href={isHome ? "#tracking" : "/#tracking"}
              className="flex items-center gap-2 px-4 py-2 text-xs uppercase tracking-wider font-bold hover:font-black bg-white/10 border border-white/10 hover:bg-white/20 text-white rounded-md transition-all duration-300 ease-out hover:shadow-[0_4px_10px_rgba(255,255,255,0.05)]"
            >
              <Package className="w-3.5 h-3.5" />
              Track Order
            </Link>

            <Link href={isHome ? "#products" : "/#products"}>
              <Button className="rounded-md flex items-center gap-2 bg-brand-accent hover:bg-brand-accent-hover text-white font-bold hover:font-black border-none text-xs uppercase tracking-wider px-5 py-2 h-9 transition-all duration-300 ease-out hover:shadow-[0_4px_10px_rgba(245,158,11,0.25)]">
                <ShoppingBag className="w-3.5 h-3.5 text-white" />
                Order Now
              </Button>
            </Link>



            {!mounted || loading ? (
              <div className="w-8 h-8 rounded-full bg-white/5 animate-pulse ml-6" />
            ) : user ? (
              <div
                className="relative flex items-center border-l border-white/10 pl-6 h-full py-4"
                onMouseEnter={() => setDropdownOpen(true)}
                onMouseLeave={() => setDropdownOpen(false)}
              >
                <button
                  className="flex items-center gap-2 focus:outline-none cursor-pointer"
                  aria-label="User Menu"
                >
                  {user.image ? (
                    <Image
                      src={user.image}
                      alt={user.name}
                      width={32}
                      height={32}
                      className="w-8 h-8 rounded-full object-cover border-2 border-brand-accent transition-transform duration-300 hover:scale-105"
                    />
                  ) : (
                    <div className="w-8 h-8 rounded-full bg-gradient-to-r from-amber-500 to-orange-600 text-white font-extrabold flex items-center justify-center text-xs border-2 border-brand-accent transition-transform duration-300 hover:scale-105">
                      {user.name?.[0]?.toUpperCase() || "U"}
                    </div>
                  )}
                </button>

                {/* Hover Dropdown Menu */}
                {dropdownOpen && (
                  <div className="absolute right-0 top-[80%] pt-2 w-48 transition-all duration-200 animate-fade-in z-50">
                    <div className="bg-brand-surface/98 border border-white/10 backdrop-blur-xl rounded-xl shadow-2xl p-1.5 space-y-1">
                      <div className="px-3 py-2 border-b border-white/5">
                        <p className="text-[10px] uppercase tracking-wider font-black text-brand-accent">Logged in as</p>
                        <p className="text-xs font-bold text-white truncate max-w-full mt-0.5">{user.name}</p>
                      </div>

                      <Link
                        href="/profile"
                        className="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-xs font-bold uppercase tracking-wider text-zinc-300 hover:bg-white/10 hover:text-white transition-all"
                      >
                        <User className="w-3.5 h-3.5 text-zinc-400" />
                        Manage Profile
                      </Link>

                      <button
                        onClick={handleLogout}
                        className="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-xs font-bold uppercase tracking-wider text-red-400 hover:bg-red-500/10 hover:text-red-300 transition-all cursor-pointer"
                      >
                        <LogOut className="w-3.5 h-3.5" />
                        Logout
                      </button>
                    </div>
                  </div>
                )}
              </div>
            ) : (
              <Link href="/login">
                <Button className="rounded-md bg-transparent hover:bg-white/10 text-white font-bold border border-white/20 text-xs uppercase tracking-wider px-5 py-2 h-9 transition-all">
                  Login
                </Button>
              </Link>
            )}

            <Button
              onClick={() => setSearchOpen(true)}
              variant="outline"
              size="icon"
              className="bg-white/10 border-white/10 hover:bg-white/20 text-white cursor-pointer hover:shadow-[0_4px_10px_rgba(255,255,255,0.05)] ml-2"
              aria-label="Search products"
              title="Search products (Ctrl+K or /)"
            >
              <Search className="w-4 h-4" />
            </Button>
          </div>

          {/* Mobile toggle */}
          <div className="flex items-center gap-2 xl:hidden">
            {!mounted || loading ? (
              <div className="w-7 h-7 rounded-full bg-white/5 animate-pulse" />
            ) : user ? (
              <div className="relative">
                <button
                  onClick={() => setMobileDropdownOpen(!mobileDropdownOpen)}
                  className="flex items-center focus:outline-none cursor-pointer"
                  aria-label="User Menu"
                >
                  {user.image ? (
                    <Image
                      src={user.image}
                      alt={user.name}
                      width={28}
                      height={28}
                      className="w-7 h-7 rounded-full object-cover border border-brand-accent transition-transform duration-300 hover:scale-105"
                    />
                  ) : (
                    <div className="w-7 h-7 rounded-full bg-gradient-to-r from-amber-500 to-orange-600 text-white font-extrabold flex items-center justify-center text-[10px] border border-brand-accent transition-transform duration-300 hover:scale-105">
                      {user.name?.[0]?.toUpperCase() || "U"}
                    </div>
                  )}
                </button>

                {/* Click-based Mobile Dropdown Menu */}
                {mobileDropdownOpen && (
                  <div className="absolute right-0 top-[120%] pt-2 w-48 transition-all duration-200 animate-fade-in z-50">
                    <div className="bg-brand-surface/98 border border-white/10 backdrop-blur-xl rounded-xl shadow-2xl p-1.5 space-y-1">
                      <div className="px-3 py-2 border-b border-white/5">
                        <p className="text-[10px] uppercase tracking-wider font-black text-brand-accent">Logged in as</p>
                        <p className="text-xs font-bold text-white truncate max-w-full mt-0.5">{user.name}</p>
                      </div>

                      <Link
                        href="/profile"
                        onClick={() => setMobileDropdownOpen(false)}
                        className="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-xs font-bold uppercase tracking-wider text-zinc-300 hover:bg-white/10 hover:text-white transition-all"
                      >
                        <User className="w-3.5 h-3.5 text-zinc-400" />
                        Manage Profile
                      </Link>

                      <button
                        onClick={() => {
                          setMobileDropdownOpen(false);
                          handleLogout();
                        }}
                        className="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-xs font-bold uppercase tracking-wider text-red-400 hover:bg-red-500/10 hover:text-red-300 transition-all cursor-pointer"
                      >
                        <LogOut className="w-3.5 h-3.5" />
                        Logout
                      </button>
                    </div>
                  </div>
                )}
              </div>
            ) : null}
            <Button
              onClick={() => setSearchOpen(true)}
              variant="ghost"
              size="icon"
              className="text-white hover:text-brand-accent hover:bg-white/5 cursor-pointer mr-1"
              aria-label="Search products"
            >
              <Search className="w-5 h-5" />
            </Button>
            <button onClick={() => setOpen(!open)} className="p-2 text-white" aria-label="Toggle navigation menu">
              {open ? <X /> : <Menu />}
            </button>
          </div>
        </div>

        {/* Mobile menu */}
        {open && (
          <div className="xl:hidden bg-brand-surface/95 backdrop-blur-lg border-t border-white/10 p-4 space-y-3">
            {navLinks.map((l) => (
              <Link
                key={l.id}
                href={isHome ? l.href : `/${l.href}`}
                onClick={(e) => handleNavClick(l.id, e)}
                className={`block text-xs uppercase tracking-wider font-bold hover:font-black transition-all py-1.5
                ${active === l.id && isHome
                    ? "text-brand-accent underline underline-offset-4 decoration-2 font-black"
                    : "text-brand-text-light hover:text-brand-accent"
                  }`}
              >
                {l.label}
              </Link>
            ))}

            {mounted && user && (
              <>
                <Link
                  href="/profile"
                  onClick={() => setOpen(false)}
                  className={`block text-xs uppercase tracking-wider font-bold hover:font-black transition-all py-1.5
                  ${pathname === "/profile"
                      ? "text-brand-accent underline underline-offset-4 decoration-2 font-black"
                      : "text-brand-text-light hover:text-brand-accent"
                    }`}
                >
                  Manage Profile
                </Link>
                <Link
                  href="/my-orders"
                  onClick={() => setOpen(false)}
                  className={`block text-xs uppercase tracking-wider font-bold hover:font-black transition-all py-1.5
                  ${pathname.startsWith("/my-orders")
                      ? "text-brand-accent underline underline-offset-4 decoration-2 font-black"
                      : "text-brand-text-light hover:text-brand-accent"
                    }`}
                >
                  My Orders
                </Link>
              </>
            )}

            {mounted && !user && (
              <Link href="/login" onClick={() => setOpen(false)} className="block py-1.5">
                <Button className="w-full rounded-md bg-transparent hover:bg-white/10 text-white font-bold border border-white/20 text-xs uppercase tracking-wider py-2">
                  Login
                </Button>
              </Link>
            )}
          </div>
        )}
      </nav>
      <SearchModal isOpen={searchOpen} onClose={() => setSearchOpen(false)} />
    </>
  );
}
