"use client";

import { useState, useEffect, useRef } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useSession, signOut } from "next-auth/react";
import {
  Search,
  ShoppingCart,
  User,
  Menu,
  X,
  ChevronDown,
  Heart,
  Phone,
  MapPin,
  Laptop,
  Smartphone,
  Tag,
  Bot,
  LayoutDashboard,
  LogOut,
  Package,
  Settings,
} from "lucide-react";
import { useCartStore } from "@/store/cart";
import { cn } from "@/lib/utils";

const navLinks = [
  {
    label: "Laptops",
    href: "/laptops",
    icon: Laptop,
    children: [
      { label: "All Laptops", href: "/laptops" },
      { label: "Gaming Laptops", href: "/laptops?tag=gaming" },
      { label: "Business Laptops", href: "/laptops?tag=business" },
      { label: "Student Laptops", href: "/laptops?tag=student" },
      { label: "Apple MacBooks", href: "/laptops?brand=apple" },
      { label: "Dell Laptops", href: "/laptops?brand=dell" },
      { label: "HP Laptops", href: "/laptops?brand=hp" },
      { label: "Lenovo Laptops", href: "/laptops?brand=lenovo" },
      { label: "ASUS Laptops", href: "/laptops?brand=asus" },
    ],
  },
  {
    label: "iPhones",
    href: "/iphones",
    icon: Smartphone,
    children: [
      { label: "All iPhones", href: "/iphones" },
      { label: "iPhone 16 Series", href: "/iphones?tag=iphone-16" },
      { label: "iPhone 15 Series", href: "/iphones?tag=iphone-15" },
      { label: "iPhone 14 Series", href: "/iphones?tag=iphone-14" },
      { label: "Refurbished iPhones", href: "/iphones?condition=refurbished" },
    ],
  },
  { label: "Deals", href: "/deals", icon: Tag },
  { label: "AI Finder", href: "/ai-finder", icon: Bot },
];

export default function Header() {
  const [mobileOpen, setMobileOpen] = useState(false);
  const [activeDropdown, setActiveDropdown] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState("");
  const [scrolled, setScrolled] = useState(false);
  const [userMenuOpen, setUserMenuOpen] = useState(false);
  const router = useRouter();
  const { data: session } = useSession();
  const { itemCount, toggleCart } = useCartStore();
  const count = itemCount();
  const dropdownRef = useRef<HTMLDivElement>(null);
  const userMenuRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 10);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
        setActiveDropdown(null);
      }
      if (userMenuRef.current && !userMenuRef.current.contains(e.target as Node)) {
        setUserMenuOpen(false);
      }
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    if (searchQuery.trim()) {
      router.push(`/search?q=${encodeURIComponent(searchQuery.trim())}`);
      setSearchQuery("");
      setMobileOpen(false);
    }
  };

  return (
    <header className={cn("sticky top-0 z-50 w-full transition-all duration-300", scrolled ? "shadow-lg" : "shadow-sm")}>
      {/* Top bar */}
      <div className="bg-gradient-to-r from-sky-800 to-sky-600 text-white text-xs py-2 hidden sm:block">
        <div className="max-w-7xl mx-auto px-4 flex justify-between items-center">
          <div className="flex items-center gap-4">
            <a href="tel:+254706127075" className="flex items-center gap-1 hover:text-sky-200 transition-colors">
              <Phone className="w-3 h-3" /> 0706 127 075
            </a>
            <span className="flex items-center gap-1">
              <MapPin className="w-3 h-3" /> Moi Avenue, Nairobi
            </span>
          </div>
          <div className="flex items-center gap-4">
            <span>&#x1F4E6; Same-Day Delivery in Nairobi</span>
            <span>&#x1F50C; 1-Year Warranty</span>
          </div>
        </div>
      </div>

      {/* Main header */}
      <div className="bg-white border-b border-sky-100">
        <div className="max-w-7xl mx-auto px-4 h-16 flex items-center gap-4">
          {/* Logo */}
          <Link href="/" className="flex items-center gap-2 shrink-0">
            <div className="w-9 h-9 rounded-xl bg-gradient-to-br from-sky-500 to-sky-700 flex items-center justify-center">
              <span className="text-white font-black text-lg">P</span>
            </div>
            <span className="text-xl font-black text-sky-700 hidden sm:block">
              Pro<span className="text-sky-500">Touch</span>
            </span>
          </Link>

          {/* Search */}
          <form onSubmit={handleSearch} className="flex-1 max-w-xl">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
              <input
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Search laptops, iPhones, accessories..."
                className="w-full pl-10 pr-4 py-2.5 rounded-xl border-2 border-sky-100 focus:border-sky-400 focus:outline-none text-sm bg-slate-50 focus:bg-white transition-all"
              />
              <button
                type="submit"
                className="absolute right-2 top-1/2 -translate-y-1/2 bg-sky-500 text-white px-3 py-1.5 rounded-lg text-xs font-medium hover:bg-sky-600 transition-colors"
              >
                Search
              </button>
            </div>
          </form>

          {/* Right actions */}
          <div className="flex items-center gap-2 shrink-0">
            {/* Wishlist */}
            <Link href="/account/wishlist" className="p-2 rounded-xl hover:bg-sky-50 transition-colors relative hidden sm:flex">
              <Heart className="w-5 h-5 text-slate-600" />
            </Link>

            {/* Cart */}
            <button
              onClick={toggleCart}
              className="p-2 rounded-xl hover:bg-sky-50 transition-colors relative"
            >
              <ShoppingCart className="w-5 h-5 text-slate-600" />
              {count > 0 && (
                <span className="absolute -top-1 -right-1 w-5 h-5 rounded-full bg-sky-500 text-white text-xs flex items-center justify-center font-bold">
                  {count > 9 ? "9+" : count}
                </span>
              )}
            </button>

            {/* User */}
            <div className="relative" ref={userMenuRef}>
              {session ? (
                <button
                  onClick={() => setUserMenuOpen(!userMenuOpen)}
                  className="flex items-center gap-2 px-3 py-2 rounded-xl hover:bg-sky-50 transition-colors"
                >
                  <div className="w-8 h-8 rounded-full bg-gradient-to-br from-sky-400 to-sky-600 flex items-center justify-center text-white text-sm font-bold">
                    {session.user?.name?.charAt(0) || "U"}
                  </div>
                  <ChevronDown className="w-3 h-3 text-slate-500 hidden sm:block" />
                </button>
              ) : (
                <Link
                  href="/login"
                  className="flex items-center gap-2 px-3 py-2 rounded-xl bg-sky-500 text-white hover:bg-sky-600 transition-colors text-sm font-medium"
                >
                  <User className="w-4 h-4" />
                  <span className="hidden sm:inline">Sign In</span>
                </Link>
              )}

              {userMenuOpen && session && (
                <div className="absolute right-0 top-full mt-2 w-52 bg-white rounded-xl shadow-xl border border-sky-100 py-2 z-50">
                  <div className="px-4 py-2 border-b border-slate-100">
                    <p className="font-semibold text-slate-800 text-sm">{session.user?.name}</p>
                    <p className="text-xs text-slate-500 truncate">{session.user?.email}</p>
                  </div>
                  <Link href="/account" onClick={() => setUserMenuOpen(false)} className="flex items-center gap-3 px-4 py-2.5 hover:bg-sky-50 text-sm text-slate-700 transition-colors">
                    <User className="w-4 h-4 text-sky-500" /> My Account
                  </Link>
                  <Link href="/account/orders" onClick={() => setUserMenuOpen(false)} className="flex items-center gap-3 px-4 py-2.5 hover:bg-sky-50 text-sm text-slate-700 transition-colors">
                    <Package className="w-4 h-4 text-sky-500" /> My Orders
                  </Link>
                  <Link href="/account/wishlist" onClick={() => setUserMenuOpen(false)} className="flex items-center gap-3 px-4 py-2.5 hover:bg-sky-50 text-sm text-slate-700 transition-colors">
                    <Heart className="w-4 h-4 text-sky-500" /> Wishlist
                  </Link>
                  {(session.user?.role === "ADMIN" || session.user?.role === "SUPER_ADMIN") && (
                    <Link href="/admin" onClick={() => setUserMenuOpen(false)} className="flex items-center gap-3 px-4 py-2.5 hover:bg-sky-50 text-sm text-slate-700 transition-colors">
                      <LayoutDashboard className="w-4 h-4 text-sky-500" /> Admin Panel
                    </Link>
                  )}
                  <Link href="/account/profile" onClick={() => setUserMenuOpen(false)} className="flex items-center gap-3 px-4 py-2.5 hover:bg-sky-50 text-sm text-slate-700 transition-colors">
                    <Settings className="w-4 h-4 text-sky-500" /> Settings
                  </Link>
                  <hr className="my-1 border-slate-100" />
                  <button
                    onClick={() => { setUserMenuOpen(false); signOut(); }}
                    className="flex items-center gap-3 px-4 py-2.5 hover:bg-red-50 text-sm text-red-600 w-full transition-colors"
                  >
                    <LogOut className="w-4 h-4" /> Sign Out
                  </button>
                </div>
              )}
            </div>

            {/* Mobile menu toggle */}
            <button
              onClick={() => setMobileOpen(!mobileOpen)}
              className="p-2 rounded-xl hover:bg-sky-50 transition-colors lg:hidden"
            >
              {mobileOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
            </button>
          </div>
        </div>
      </div>

      {/* Nav bar */}
      <nav className="bg-gradient-to-r from-sky-700 to-sky-500 hidden lg:block" ref={dropdownRef}>
        <div className="max-w-7xl mx-auto px-4">
          <ul className="flex items-center gap-1">
            <li>
              <Link href="/" className="flex items-center gap-1 px-4 py-3 text-white/90 hover:text-white hover:bg-white/10 rounded-lg text-sm font-medium transition-all">
                Home
              </Link>
            </li>
            {navLinks.map((link) => (
              <li key={link.label} className="relative">
                {link.children ? (
                  <>
                    <button
                      onMouseEnter={() => setActiveDropdown(link.label)}
                      onMouseLeave={() => setActiveDropdown(null)}
                      className="flex items-center gap-1 px-4 py-3 text-white/90 hover:text-white hover:bg-white/10 rounded-lg text-sm font-medium transition-all"
                    >
                      {link.label}
                      <ChevronDown className="w-3.5 h-3.5" />
                    </button>
                    {activeDropdown === link.label && (
                      <div
                        onMouseEnter={() => setActiveDropdown(link.label)}
                        onMouseLeave={() => setActiveDropdown(null)}
                        className="absolute top-full left-0 mt-1 bg-white rounded-xl shadow-2xl border border-sky-100 py-2 min-w-52 z-50"
                      >
                        {link.children.map((child) => (
                          <Link
                            key={child.label}
                            href={child.href}
                            className="block px-4 py-2.5 text-sm text-slate-700 hover:bg-sky-50 hover:text-sky-700 transition-colors"
                          >
                            {child.label}
                          </Link>
                        ))}
                      </div>
                    )}
                  </>
                ) : (
                  <Link
                    href={link.href}
                    className="flex items-center gap-1 px-4 py-3 text-white/90 hover:text-white hover:bg-white/10 rounded-lg text-sm font-medium transition-all"
                  >
                    {link.label === "AI Finder" && <Bot className="w-3.5 h-3.5" />}
                    {link.label}
                  </Link>
                )}
              </li>
            ))}
            <li className="ml-auto">
              <Link
                href="/about"
                className="flex items-center gap-1 px-4 py-3 text-white/90 hover:text-white hover:bg-white/10 rounded-lg text-sm font-medium transition-all"
              >
                About
              </Link>
            </li>
            <li>
              <Link
                href="/contact"
                className="flex items-center gap-1 px-4 py-3 text-white/90 hover:text-white hover:bg-white/10 rounded-lg text-sm font-medium transition-all"
              >
                Contact
              </Link>
            </li>
          </ul>
        </div>
      </nav>

      {/* Mobile menu */}
      {mobileOpen && (
        <div className="lg:hidden bg-white border-b shadow-lg">
          <div className="max-w-7xl mx-auto px-4 py-3">
            {/* Mobile search */}
            <form onSubmit={handleSearch} className="mb-4">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                <input
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  placeholder="Search products..."
                  className="w-full pl-10 pr-4 py-2.5 rounded-xl border-2 border-sky-100 focus:border-sky-400 focus:outline-none text-sm"
                />
              </div>
            </form>

            {/* Mobile nav links */}
            <ul className="space-y-1">
              <li>
                <Link href="/" onClick={() => setMobileOpen(false)} className="flex items-center gap-3 px-3 py-2.5 rounded-lg text-slate-700 hover:bg-sky-50 hover:text-sky-700 text-sm font-medium transition-colors">
                  Home
                </Link>
              </li>
              {navLinks.map((link) => (
                <li key={link.label}>
                  <Link href={link.href} onClick={() => setMobileOpen(false)} className="flex items-center gap-3 px-3 py-2.5 rounded-lg text-slate-700 hover:bg-sky-50 hover:text-sky-700 text-sm font-medium transition-colors">
                    {link.icon && <link.icon className="w-4 h-4 text-sky-500" />}
                    {link.label}
                  </Link>
                  {link.children && (
                    <ul className="ml-7 space-y-1 mt-1">
                      {link.children.map((child) => (
                        <li key={child.label}>
                          <Link href={child.href} onClick={() => setMobileOpen(false)} className="block px-3 py-2 rounded-lg text-slate-500 hover:bg-sky-50 hover:text-sky-600 text-sm transition-colors">
                            {child.label}
                          </Link>
                        </li>
                      ))}
                    </ul>
                  )}
                </li>
              ))}
              <li>
                <Link href="/about" onClick={() => setMobileOpen(false)} className="flex items-center gap-3 px-3 py-2.5 rounded-lg text-slate-700 hover:bg-sky-50 text-sm font-medium transition-colors">
                  About
                </Link>
              </li>
              <li>
                <Link href="/contact" onClick={() => setMobileOpen(false)} className="flex items-center gap-3 px-3 py-2.5 rounded-lg text-slate-700 hover:bg-sky-50 text-sm font-medium transition-colors">
                  Contact
                </Link>
              </li>
            </ul>

            {!session && (
              <div className="mt-4 flex gap-2">
                <Link href="/login" onClick={() => setMobileOpen(false)} className="flex-1 text-center py-2.5 rounded-xl border-2 border-sky-500 text-sky-600 font-medium text-sm hover:bg-sky-50 transition-colors">
                  Sign In
                </Link>
                <Link href="/register" onClick={() => setMobileOpen(false)} className="flex-1 text-center py-2.5 rounded-xl bg-sky-500 text-white font-medium text-sm hover:bg-sky-600 transition-colors">
                  Register
                </Link>
              </div>
            )}
          </div>
        </div>
      )}
    </header>
  );
}
