import { Link, useNavigate } from "@tanstack/react-router";
import { Search, ShoppingCart, User as UserIcon, Store as StoreIcon, Menu, Bell } from "lucide-react";
import { useMemo, useState, useRef, useEffect } from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { useStore, fmt } from "@/lib/store";
import { CATEGORIES, slugify } from "@/lib/categories";
import { NotificationDrawer } from "@/components/site/NotificationDrawer";

export function Header({ onOpenCart, onOpenSignIn }: { onOpenCart?: () => void; onOpenSignIn?: () => void }) {
  const { cart, user, getAllProducts, notifications, fetchNotifications } = useStore();
  const [q, setQ] = useState("");
  const [open, setOpen] = useState(false);
  const [notifOpen, setNotifOpen] = useState(false);
  const wrap = useRef<HTMLDivElement>(null);
  const navigate = useNavigate();
  const cartCount = cart.reduce((s, x) => s + x.qty, 0);
  const unreadNotifs = notifications.filter((n) => !n.is_read).length;

  const results = useMemo(() => {
    const t = q.trim().toLowerCase();
    if (!t) return [];
    return getAllProducts()
      .filter((p) => p.name.toLowerCase().includes(t) || (p.category ?? "").toLowerCase().includes(t))
      .slice(0, 8);
  }, [q, getAllProducts]);

  useEffect(() => {
    fetchNotifications();
    const interval = setInterval(() => {
      fetchNotifications();
    }, 12000);
    return () => clearInterval(interval);
  }, [user?.email, fetchNotifications]);

  useEffect(() => {
    const onDoc = (e: MouseEvent) => {
      if (!wrap.current?.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, []);

  return (
    <>
      <NotificationDrawer open={notifOpen} onOpenChange={setNotifOpen} />
      <div className="bg-neutral-800 text-white text-xs">
        <div className="max-w-[1200px] mx-auto px-4 py-1.5 flex gap-4">
          <Link to="/vendor" className="hover:text-orange-400">Sell on SulejaMarket</Link>
          <Link to="/admin" className="hover:text-orange-400 ml-auto">Admin</Link>
          <Link to="/profile" className="hover:text-orange-400">My Account</Link>
        </div>
      </div>
      <header className="bg-white border-b sticky top-0 z-30">
        <div className="max-w-[1200px] mx-auto px-4 py-3 flex flex-wrap items-center justify-between gap-3 md:gap-6">
          <Link to="/" className="text-2xl font-extrabold text-orange-500 tracking-tight shrink-0">
            SULEJA<span className="text-neutral-800">MARKETS</span>
            <span className="inline-block w-2 h-2 rounded-full bg-orange-500 ml-0.5" />
          </Link>
          <div className="w-full order-3 md:order-2 md:flex-1 flex gap-2">
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="outline" size="icon" className="h-10 w-10 shrink-0 rounded-full lg:hidden text-neutral-600 bg-neutral-100 border-neutral-200">
                  <Menu className="w-5 h-5" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="start" className="w-56 max-h-[70vh] overflow-y-auto">
                <div className="px-2 py-1.5 text-sm font-bold text-neutral-500">Categories</div>
                {CATEGORIES.map((c) => (
                  <DropdownMenuItem key={c} asChild>
                    <Link to="/category/$slug" params={{ slug: slugify(c) }} className="cursor-pointer">{c}</Link>
                  </DropdownMenuItem>
                ))}
              </DropdownMenuContent>
            </DropdownMenu>

            <div ref={wrap} className="flex-1 relative">
              <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-neutral-400" />
            <Input
              value={q}
              onChange={(e) => { setQ(e.target.value); setOpen(true); }}
              onFocus={() => setOpen(true)}
              placeholder="Search products, brands and categories"
              className="pl-9 pr-24 h-10 rounded-full bg-neutral-100 border-neutral-200 w-full"
            />
            <Button className="absolute right-1 top-1/2 -translate-y-1/2 h-8 rounded-full bg-orange-500 hover:bg-orange-600 px-6 text-white">
              Search
            </Button>
            {open && q && (
              <div className="absolute left-0 right-0 top-12 bg-white border rounded-md shadow-lg z-40 max-h-[420px] overflow-y-auto">
                {results.length === 0 ? (
                  <div className="p-4 text-sm text-neutral-500">No products match "{q}"</div>
                ) : (
                  results.map((p) => (
                    <button
                      key={p.id}
                      onClick={() => { setOpen(false); setQ(""); navigate({ to: "/", hash: p.id }); }}
                      className="w-full flex items-center gap-3 p-2.5 hover:bg-orange-50 text-left border-b last:border-0"
                    >
                      <img
                        src={(p.images?.[0] || `https://picsum.photos/seed/${p.seed}/60/60`)}
                        alt={p.name}
                        className="w-11 h-11 rounded object-cover flex-shrink-0"
                      />
                      <div className="flex-1 min-w-0">
                        <div className="text-sm text-neutral-800 line-clamp-1">{p.name}</div>
                        <div className="text-xs text-neutral-500">{p.category || "Product"}</div>
                      </div>
                      <div className="text-sm font-bold text-orange-600">₦ {fmt(p.price)}</div>
                    </button>
                  ))
                )}
              </div>
            )}
            </div>
          </div>
          <nav className="flex items-center gap-3 sm:gap-5 text-sm order-2 md:order-3 shrink-0">
            <button 
              onClick={() => setNotifOpen(true)} 
              className="relative p-1.5 text-neutral-700 hover:text-orange-500 transition rounded-full hover:bg-orange-50"
              title="In-App Notifications"
            >
              <Bell className="w-5 h-5" />
              {unreadNotifs > 0 && (
                <span className="absolute -top-1 -right-1 bg-orange-500 text-white text-[10px] font-extrabold rounded-full min-w-4 h-4 px-1 flex items-center justify-center animate-bounce shadow-xs">
                  {unreadNotifs}
                </span>
              )}
            </button>
            <button onClick={onOpenSignIn} className="flex items-center gap-1.5 hover:text-orange-500">
              <UserIcon className="w-4 h-4" />
              {user ? user.name : "Account"}
            </button>
            <Link to="/vendor" className="flex items-center gap-1.5 hover:text-orange-500">
              <StoreIcon className="w-4 h-4" /> Vendor
            </Link>
            <button onClick={onOpenCart} className="relative flex items-center gap-1 hover:text-orange-500">
              <ShoppingCart className="w-5 h-5" />
              <span>Cart</span>
              {cartCount > 0 && (
                <span className="absolute -top-2 -right-3 bg-orange-500 text-white text-[10px] font-bold rounded-full w-5 h-5 flex items-center justify-center">
                  {cartCount}
                </span>
              )}
            </button>
          </nav>
        </div>
      </header>
    </>
  );
}
