import { useEffect, useRef, useState } from "react";
import { Link, useLocation } from "wouter";
import { useLanguage } from "../../contexts/LanguageContext";
import { useAuth } from "../../contexts/AuthContext";
import { useCart } from "../../contexts/CartContext";
import { Button } from "../ui/button";
import {
  Search,
  ShoppingCart,
  User,
  ChevronDown,
  Menu,
  X,
  LogOut,
  Globe,
  Sprout,
  HandCoins,
  Gift,
  Beef,
  Megaphone,
  Repeat,
  MessageSquare,
  TrendingUp,
  HeartHandshake,
  Info,
  Users,
} from "lucide-react";
import ehsanLogo from "../../assets/ehsan-logo.png";

export function Header() {
  const { language, setLanguage, t } = useLanguage();
  const { isAuthenticated, logout } = useAuth();
  const { count: cartCount } = useCart();
  const [location, setLocation] = useLocation();
  const [mobileOpen, setMobileOpen] = useState(false);
  const [servicesOpen, setServicesOpen] = useState(false);
  const [aboutOpen, setAboutOpen] = useState(false);
  const servicesTriggerRef = useRef<HTMLButtonElement>(null);
  const servicesPanelRef = useRef<HTMLDivElement>(null);
  const aboutTriggerRef = useRef<HTMLButtonElement>(null);
  const aboutPanelRef = useRef<HTMLDivElement>(null);

  const toggleLanguage = () => setLanguage(language === "ar" ? "en" : "ar");

  const isActive = (path: string) => location === path;

  const handleServiceClick = (path: string) => {
    setServicesOpen(false);
    setLocation(path);
  };

  const handleAboutClick = (path: string) => {
    setAboutOpen(false);
    setLocation(path);
  };

  useEffect(() => {
    if (!servicesOpen) return;
    const onPointerDown = (e: MouseEvent) => {
      const target = e.target as Node;
      if (
        servicesPanelRef.current?.contains(target) ||
        servicesTriggerRef.current?.contains(target)
      ) {
        return;
      }
      setServicesOpen(false);
    };
    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") setServicesOpen(false);
    };
    document.addEventListener("mousedown", onPointerDown);
    document.addEventListener("keydown", onKeyDown);
    return () => {
      document.removeEventListener("mousedown", onPointerDown);
      document.removeEventListener("keydown", onKeyDown);
    };
  }, [servicesOpen]);

  useEffect(() => {
    if (!aboutOpen) return;
    const onPointerDown = (e: MouseEvent) => {
      const target = e.target as Node;
      if (
        aboutPanelRef.current?.contains(target) ||
        aboutTriggerRef.current?.contains(target)
      ) {
        return;
      }
      setAboutOpen(false);
    };
    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") setAboutOpen(false);
    };
    document.addEventListener("mousedown", onPointerDown);
    document.addEventListener("keydown", onKeyDown);
    return () => {
      document.removeEventListener("mousedown", onPointerDown);
      document.removeEventListener("keydown", onKeyDown);
    };
  }, [aboutOpen]);

  const services = [
    { key: "ghiras", label: t.serviceItems.ghiras, icon: Sprout },
    { key: "zakat", label: t.serviceItems.zakat, icon: HandCoins },
    { key: "gift", label: t.serviceItems.gift, icon: Gift },
    { key: "adahi", label: t.serviceItems.adahi, icon: Beef },
    { key: "campaigns", label: t.serviceItems.campaigns, icon: Megaphone },
    { key: "recurring", label: t.serviceItems.recurring, icon: Repeat },
    { key: "sms", label: t.serviceItems.sms, icon: MessageSquare },
    { key: "stocks", label: t.serviceItems.stocks, icon: TrendingUp },
  ];

  return (
    <header className="bg-white sticky top-0 z-50 shadow-sm relative">
      <div className="container mx-auto px-4 h-16 flex items-center justify-between gap-4">
        {/* Logo */}
        <Link href="/" className="flex items-center shrink-0">
          <img src={ehsanLogo} alt={t.common.ehsan} className="h-11 w-auto object-contain" />
        </Link>

        {/* Desktop nav */}
        <nav className="hidden lg:flex items-stretch self-stretch gap-1 flex-1 justify-center">
          <Link
            href="/"
            className={`px-4 flex items-center text-sm font-medium transition-colors ${
              isActive("/")
                ? "bg-[#1B8354] text-white font-bold rounded-b-lg"
                : "text-foreground hover:text-primary"
            }`}
            data-testid="nav-home"
          >
            {t.nav.home}
          </Link>

          <Link
            href="/waqf"
            className={`px-4 flex items-center text-sm font-medium transition-colors ${
              isActive("/waqf")
                ? "bg-[#1B8354] text-white font-bold rounded-b-lg"
                : "text-foreground hover:text-primary"
            }`}
            data-testid="nav-waqf"
          >
            {t.nav.waqf}
          </Link>

          <Link
            href="/opportunities"
            className={`px-4 flex items-center gap-1 text-sm transition-colors ${
              isActive("/opportunities")
                ? "bg-[#1B8354] text-white font-bold rounded-b-lg"
                : "text-foreground font-medium hover:text-primary"
            }`}
            data-testid="nav-opportunities"
          >
            {t.nav.opportunities}
            <ChevronDown className="w-3.5 h-3.5" />
          </Link>

          <button
            ref={servicesTriggerRef}
            type="button"
            onClick={() => setServicesOpen((v) => !v)}
            className={`px-3 flex items-center gap-1 text-sm font-medium transition-colors ${
              servicesOpen ? "text-primary" : "text-foreground hover:text-primary"
            }`}
            data-testid="nav-services"
            aria-haspopup="menu"
            aria-controls="services-megamenu"
            aria-expanded={servicesOpen}
          >
            {t.nav.services}
            <ChevronDown
              className={`w-3.5 h-3.5 transition-transform ${servicesOpen ? "rotate-180" : ""}`}
            />
          </button>

          <button
            ref={aboutTriggerRef}
            type="button"
            onClick={() => setAboutOpen((v) => !v)}
            className={`px-3 flex items-center gap-1 text-sm font-medium transition-colors ${
              aboutOpen || location.startsWith("/about")
                ? "text-primary"
                : "text-foreground hover:text-primary"
            }`}
            data-testid="nav-about"
            aria-haspopup="menu"
            aria-controls="about-menu"
            aria-expanded={aboutOpen}
          >
            {t.nav.about}
            <ChevronDown
              className={`w-3.5 h-3.5 transition-transform ${aboutOpen ? "rotate-180" : ""}`}
            />
          </button>

          <Link
            href="/baraem"
            className={`px-4 flex items-center text-sm font-medium transition-colors ${
              isActive("/baraem")
                ? "bg-[#1B8354] text-white font-bold rounded-b-lg"
                : "text-foreground hover:text-primary"
            }`}
            data-testid="nav-baraem"
          >
            {t.nav.baraem}
          </Link>
        </nav>

        {/* Utility icons */}
        <div className="flex items-center gap-1 shrink-0">
          {isAuthenticated ? (
            <Button
              variant="ghost"
              size="sm"
              className="gap-1.5 hidden sm:inline-flex"
              onClick={() => { logout(); setLocation("/"); }}
              data-testid="button-logout"
            >
              <LogOut className="w-4 h-4" />
              <span className="hidden md:inline">{t.common.logout}</span>
            </Button>
          ) : (
            <Link
              href="/login"
              className="hidden sm:inline-flex items-center gap-1.5 px-2.5 py-2 text-sm font-medium text-foreground hover:text-primary transition-colors"
              data-testid="button-login"
            >
              <User className="w-4 h-4" />
              <span className="hidden md:inline">{t.common.login}</span>
            </Link>
          )}

          <Button
            variant="ghost"
            size="icon"
            className="text-foreground relative"
            aria-label={t.common.cart}
            onClick={() => setLocation("/cart")}
            data-testid="button-cart"
          >
            <ShoppingCart className="w-4 h-4" />
            {cartCount > 0 && (
              <span
                className="absolute -top-1 -end-1 min-w-[1.1rem] h-[1.1rem] px-1 rounded-full bg-primary text-primary-foreground text-[0.65rem] font-bold flex items-center justify-center leading-none"
                data-testid="badge-cart-count"
              >
                {cartCount}
              </span>
            )}
          </Button>
          <Button
            variant="ghost"
            size="icon"
            className="text-foreground"
            aria-label={t.common.search}
            onClick={() => setLocation("/")}
            data-testid="button-search"
          >
            <Search className="w-4 h-4" />
          </Button>
          <Button
            variant="ghost"
            size="sm"
            onClick={toggleLanguage}
            className="gap-1.5 font-medium"
            data-testid="button-language"
          >
            <Globe className="w-4 h-4" />
            <span className="hidden md:inline">{t.common.language}</span>
          </Button>

          {/* Mobile menu toggle */}
          <Button
            variant="ghost"
            size="icon"
            className="lg:hidden text-foreground"
            onClick={() => setMobileOpen((v) => !v)}
            aria-label="Menu"
            data-testid="button-mobileMenu"
          >
            {mobileOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
          </Button>
        </div>
      </div>

      {/* Services mega-menu (desktop) */}
      {servicesOpen && (
        <div
          ref={servicesPanelRef}
          id="services-megamenu"
          role="menu"
          className="hidden lg:block absolute inset-x-0 top-full border-t bg-white shadow-lg"
          data-testid="services-megamenu"
          onMouseLeave={() => setServicesOpen(false)}
        >
          <div className="container mx-auto px-4 py-4">
            <div className="flex items-stretch">
              {services.map((s, i) => (
                <button
                  key={s.key}
                  type="button"
                  onClick={() => handleServiceClick("/opportunities")}
                  data-testid={`nav-service-${s.key}`}
                  className={`flex-1 flex flex-col items-center justify-center gap-2 px-2 py-3 rounded-md text-center hover:bg-muted transition-colors ${
                    i > 0 ? "border-s border-border" : ""
                  }`}
                >
                  <s.icon className="w-7 h-7 text-primary" />
                  <span className="text-sm font-medium text-foreground">{s.label}</span>
                </button>
              ))}
              <button
                type="button"
                onClick={() => handleServiceClick("/request")}
                data-testid="nav-requestSupport"
                className="flex-1 flex flex-col items-center justify-center gap-2 px-2 py-3 rounded-md text-center bg-muted/40 hover:bg-muted transition-colors border-s border-border"
              >
                <HeartHandshake className="w-7 h-7 text-primary" />
                <span className="text-sm font-semibold text-primary">{t.nav.requestSupport}</span>
              </button>
            </div>
          </div>
        </div>
      )}

      {/* About dropdown (desktop) */}
      {aboutOpen && (
        <div
          ref={aboutPanelRef}
          id="about-menu"
          role="menu"
          className="hidden lg:block absolute inset-x-0 top-full border-t bg-white shadow-lg"
          data-testid="about-menu"
          onMouseLeave={() => setAboutOpen(false)}
        >
          <div className="container mx-auto px-4 py-4">
            <div className="flex items-stretch gap-2 max-w-md">
              <button
                type="button"
                onClick={() => handleAboutClick("/about")}
                data-testid="nav-about-whoWeAre"
                className="flex-1 flex flex-col items-center justify-center gap-2 px-2 py-3 rounded-md text-center hover:bg-muted transition-colors"
              >
                <Info className="w-7 h-7 text-primary" />
                <span className="text-sm font-medium text-foreground">{t.about.whoWeAre}</span>
              </button>
              <button
                type="button"
                onClick={() => handleAboutClick("/about/committees")}
                data-testid="nav-about-committees"
                className="flex-1 flex flex-col items-center justify-center gap-2 px-2 py-3 rounded-md text-center hover:bg-muted transition-colors border-s border-border"
              >
                <Users className="w-7 h-7 text-primary" />
                <span className="text-sm font-medium text-foreground">{t.about.committees}</span>
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Mobile nav panel */}
      {mobileOpen && (
        <div className="lg:hidden border-t bg-white px-4 py-3 space-y-1">
          <Link
            href="/"
            onClick={() => setMobileOpen(false)}
            className={`block px-3 py-2 rounded-md text-sm hover:bg-muted ${
              isActive("/")
                ? "bg-[#1B8354] text-white font-bold"
                : "text-foreground font-medium"
            }`}
          >
            {t.nav.home}
          </Link>
          <Link
            href="/waqf"
            onClick={() => setMobileOpen(false)}
            className={`block px-3 py-2 rounded-md text-sm hover:bg-muted ${
              isActive("/waqf")
                ? "bg-[#1B8354] text-white font-bold"
                : "text-foreground font-medium"
            }`}
          >
            {t.nav.waqf}
          </Link>
          <Link
            href="/opportunities"
            onClick={() => setMobileOpen(false)}
            className={`block px-3 py-2 rounded-md text-sm hover:bg-muted ${
              isActive("/opportunities")
                ? "bg-[#1B8354] text-white font-bold"
                : "text-foreground font-medium"
            }`}
          >
            {t.nav.opportunities}
          </Link>
          <div className="pt-1">
            <p className="px-3 py-1 text-xs font-semibold text-foreground/50">
              {t.nav.services}
            </p>
            {services.map((s) => (
              <button
                key={s.key}
                onClick={() => { setMobileOpen(false); setLocation("/opportunities"); }}
                className="flex w-full items-center gap-2 text-start px-3 py-2 rounded-md text-sm font-medium text-foreground hover:bg-muted"
              >
                <s.icon className="w-4 h-4 text-primary" />
                <span>{s.label}</span>
              </button>
            ))}
          </div>
          <Link
            href="/request"
            onClick={() => setMobileOpen(false)}
            className={`block px-3 py-2 rounded-md text-sm font-medium hover:bg-muted ${
              isActive("/request") ? "text-primary bg-muted" : "text-foreground"
            }`}
          >
            {t.nav.requestSupport}
          </Link>
          <div className="pt-1">
            <p className="px-3 py-1 text-xs font-semibold text-foreground/50">
              {t.nav.about}
            </p>
            <Link
              href="/about"
              onClick={() => setMobileOpen(false)}
              className="flex w-full items-center gap-2 text-start px-3 py-2 rounded-md text-sm font-medium text-foreground hover:bg-muted"
            >
              <Info className="w-4 h-4 text-primary" />
              <span>{t.about.whoWeAre}</span>
            </Link>
            <Link
              href="/about/committees"
              onClick={() => setMobileOpen(false)}
              className="flex w-full items-center gap-2 text-start px-3 py-2 rounded-md text-sm font-medium text-foreground hover:bg-muted"
            >
              <Users className="w-4 h-4 text-primary" />
              <span>{t.about.committees}</span>
            </Link>
          </div>
          <Link
            href="/baraem"
            onClick={() => setMobileOpen(false)}
            className={`block px-3 py-2 rounded-md text-sm hover:bg-muted ${
              isActive("/baraem")
                ? "bg-[#1B8354] text-white font-bold"
                : "text-foreground font-medium"
            }`}
          >
            {t.nav.baraem}
          </Link>
          <div className="pt-2 mt-2 border-t">
            {isAuthenticated ? (
              <>
                <Link
                  href="/admin"
                  onClick={() => setMobileOpen(false)}
                  className="block px-3 py-2 rounded-md text-sm font-medium text-foreground hover:bg-muted"
                >
                  {t.nav.admin}
                </Link>
                <button
                  onClick={() => { logout(); setMobileOpen(false); setLocation("/"); }}
                  className="block w-full text-start px-3 py-2 rounded-md text-sm font-medium text-foreground hover:bg-muted"
                >
                  {t.common.logout}
                </button>
              </>
            ) : (
              <Link
                href="/login"
                onClick={() => setMobileOpen(false)}
                className="block px-3 py-2 rounded-md text-sm font-medium text-foreground hover:bg-muted"
              >
                {t.common.login}
              </Link>
            )}
          </div>
        </div>
      )}
    </header>
  );
}
