"use client";

import React, { useState, useRef, useEffect } from "react";
import Link from "next/link";
import Image from "next/image";
import { usePathname, useRouter } from "next/navigation";
import { 
  Menu, 
  X, 
  ArrowRight, 
  ChevronDown, 
  LogOut, 
  User, 
  Lock, 
  LogIn, 
  UserPlus, 
  Layers,
  Phone,
  Mail,
  MapPin,
  Globe,
  Coins,
  Check,
  Sparkles
} from "lucide-react";
import { ThemeToggle } from "@/components/ui/ThemeToggle";
import { ShinyButton } from "@/components/ui/ShinyButton";
import { useAppStore } from "@/lib/store";
import { LANGUAGES, CURRENCIES } from "@/lib/i18n";
import { SupportedLanguage, SupportedCurrency } from "@/types";

export function Navbar() {
  const pathname = usePathname();
  const router = useRouter();
  const { 
    currentUser, 
    logout, 
    siteSettings, 
    language, 
    setLanguage, 
    currency, 
    setCurrency, 
    t 
  } = useAppStore();
  
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [authDropdownOpen, setAuthDropdownOpen] = useState(false);
  const [langDropdownOpen, setLangDropdownOpen] = useState(false);
  const [currDropdownOpen, setCurrDropdownOpen] = useState(false);

  const authDropdownRef = useRef<HTMLDivElement>(null);
  const langDropdownRef = useRef<HTMLDivElement>(null);
  const currDropdownRef = useRef<HTMLDivElement>(null);

  // Close dropdowns when clicking outside
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (authDropdownRef.current && !authDropdownRef.current.contains(event.target as Node)) {
        setAuthDropdownOpen(false);
      }
      if (langDropdownRef.current && !langDropdownRef.current.contains(event.target as Node)) {
        setLangDropdownOpen(false);
      }
      if (currDropdownRef.current && !currDropdownRef.current.contains(event.target as Node)) {
        setCurrDropdownOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  // Hide public navbar inside full admin dashboard layout
  if (pathname.startsWith("/admin") && pathname !== "/admin/login") {
    return null;
  }

  const isClient = currentUser?.role === "client";
  const portalHref = isClient ? "/portal" : "/admin/dashboard";

  const handleLogout = () => {
    logout();
    setAuthDropdownOpen(false);
    router.push("/");
  };

  const contactPhone = siteSettings?.contact_phone || "+92 335 7758256";
  const contactEmail = siteSettings?.contact_email || "contact@aethersoftinnovations.com";

  const currentLangObj = LANGUAGES.find((l) => l.code === language) || LANGUAGES[0];
  const currentCurrObj = CURRENCIES[currency] || CURRENCIES.PKR;

  const navItems = [
    { name: t("nav.home"), href: "/" },
    { name: t("nav.services"), href: "/services" },
    { name: t("nav.saas"), href: "/products" },
    { name: t("nav.packages"), href: "/packages" },
    { name: t("nav.portfolio"), href: "/portfolio" },
    { name: t("nav.team"), href: "/team" },
    { name: t("nav.contact"), href: "/contact" },
  ];

  return (
    <header className="sticky top-0 z-40 w-full font-sans">
      {/* 1. TOP UTILITY BAR (Contacts, Multi-Language, Multi-Currency, Theme, Portal) */}
      <div className="relative z-50 w-full border-b border-border/70 bg-card/95 backdrop-blur-md text-xs">
        <div className="mx-auto flex h-9 max-w-[1440px] items-center justify-between px-4 sm:px-8 font-mono text-[11px] text-muted-foreground">
          {/* Left: Direct Contact Information */}
          <div className="flex items-center gap-4 sm:gap-6">
            <a
              href={`tel:${contactPhone.replace(/\s+/g, "")}`}
              className="flex items-center gap-1.5 text-muted-foreground hover:text-[#024d37] transition-colors"
            >
              <Phone className="h-3 w-3 text-[#024d37]" />
              <span className="hidden sm:inline">{contactPhone}</span>
              <span className="sm:hidden">Call</span>
            </a>

            <a
              href={`mailto:${contactEmail}`}
              className="hidden md:flex items-center gap-1.5 text-muted-foreground hover:text-[#024d37] transition-colors"
            >
              <Mail className="h-3 w-3 text-[#024d37]" />
              <span>{contactEmail}</span>
            </a>

            <div className="hidden lg:flex items-center gap-1.5 text-muted-foreground/80">
              <MapPin className="h-3 w-3 text-[#024d37]" />
              <span>{t("topbar.location")}</span>
            </div>
          </div>

          {/* Right: Language Switcher, Currency Selector, Theme Toggle & Portal Access */}
          <div className="flex items-center gap-2.5 sm:gap-3.5">
            {/* Multi-Language Selector Dropdown */}
            <div className="relative z-50" ref={langDropdownRef}>
              <button
                onClick={() => setLangDropdownOpen(!langDropdownOpen)}
                className="flex items-center gap-1.5 rounded-md px-2 py-0.5 hover:bg-muted text-foreground transition-colors cursor-pointer"
                aria-label="Select Language"
              >
                <Globe className="h-3 w-3 text-[#024d37]" />
                <span className="font-sans font-medium">{currentLangObj.flag} {currentLangObj.code.toUpperCase()}</span>
                <ChevronDown className={`h-2.5 w-2.5 text-muted-foreground transition-transform ${langDropdownOpen ? "rotate-180" : ""}`} />
              </button>

              {langDropdownOpen && (
                <div className="absolute right-0 mt-2 w-44 rounded-xl border border-border bg-card p-1.5 shadow-2xl z-[100] space-y-0.5 animate-in fade-in zoom-in-95 duration-100 font-sans">
                  <div className="px-2 py-1 text-[10px] uppercase font-mono text-muted-foreground font-semibold border-b border-border/60">
                    // SELECT LANGUAGE
                  </div>
                  {LANGUAGES.map((lang) => (
                    <button
                      key={lang.code}
                      onClick={() => {
                        setLanguage(lang.code);
                        setLangDropdownOpen(false);
                      }}
                      className={`w-full flex items-center justify-between rounded-lg px-2.5 py-1.5 text-xs transition-colors text-left cursor-pointer ${
                        language === lang.code
                          ? "bg-[#024d37] text-white font-semibold shadow-xs"
                          : "text-foreground hover:bg-muted"
                      }`}
                    >
                      <span className="flex items-center gap-2">
                        <span>{lang.flag}</span>
                        <span>{lang.nativeName}</span>
                      </span>
                      {language === lang.code && <Check className="h-3 w-3" />}
                    </button>
                  ))}
                </div>
              )}
            </div>

            <div className="h-3 w-px bg-border" />

            {/* Multi-Currency Selector Dropdown */}
            <div className="relative z-50" ref={currDropdownRef}>
              <button
                onClick={() => setCurrDropdownOpen(!currDropdownOpen)}
                className="flex items-center gap-1.5 rounded-md px-2 py-0.5 hover:bg-muted text-foreground transition-colors cursor-pointer"
                aria-label="Select Currency"
              >
                <Coins className="h-3 w-3 text-[#024d37]" />
                <span className="font-sans font-medium">{currentCurrObj.symbol} {currentCurrObj.code}</span>
                <ChevronDown className={`h-2.5 w-2.5 text-muted-foreground transition-transform ${currDropdownOpen ? "rotate-180" : ""}`} />
              </button>

              {currDropdownOpen && (
                <div className="absolute right-0 mt-2 w-48 rounded-xl border border-border bg-card p-1.5 shadow-2xl z-[100] space-y-0.5 animate-in fade-in zoom-in-95 duration-100 font-sans">
                  <div className="px-2 py-1 text-[10px] uppercase font-mono text-muted-foreground font-semibold border-b border-border/60">
                    // SELECT CURRENCY
                  </div>
                  {(Object.keys(CURRENCIES) as SupportedCurrency[]).map((cCode) => {
                    const cInfo = CURRENCIES[cCode];
                    const isSelected = currency === cCode;
                    return (
                      <button
                        key={cCode}
                        onClick={() => {
                          setCurrency(cCode);
                          setCurrDropdownOpen(false);
                        }}
                        className={`w-full flex items-center justify-between rounded-lg px-2.5 py-1.5 text-xs transition-colors text-left cursor-pointer ${
                          isSelected
                            ? "bg-[#024d37] text-white font-semibold shadow-xs"
                            : "text-foreground hover:bg-muted"
                        }`}
                      >
                        <span className="flex items-center gap-2">
                          <span className="font-mono font-bold">{cInfo.symbol}</span>
                          <span>{cInfo.name} ({cInfo.code})</span>
                        </span>
                        {isSelected && <Check className="h-3 w-3" />}
                      </button>
                    );
                  })}
                </div>
              )}
            </div>

            <div className="h-3 w-px bg-border hidden sm:block" />

            {/* Theme Toggle in Topbar */}
            <div className="flex items-center">
              <ThemeToggle />
            </div>

            <div className="h-3 w-px bg-border hidden sm:block" />

            {/* User Account / Portal Sign-In Dropdown */}
            <div className="relative z-50" ref={authDropdownRef}>
              <button
                onClick={() => setAuthDropdownOpen(!authDropdownOpen)}
                className={`flex items-center gap-1.5 rounded-full px-2.5 py-0.5 font-sans font-medium text-xs transition-all cursor-pointer ${
                  currentUser
                    ? "bg-[#024d37]/10 text-foreground border border-[#024d37]/40"
                    : "hover:bg-muted text-foreground border border-border bg-muted/30"
                }`}
              >
                {currentUser ? (
                  <>
                    <span className="h-2 w-2 rounded-full bg-[#024d37] animate-pulse" />
                    <span className="font-semibold">{currentUser.name.split(" ")[0]}</span>
                    <span className="rounded bg-muted px-1.5 py-0.2 font-mono text-[9px] uppercase font-bold text-muted-foreground">
                      {currentUser.role === "client" ? "Client" : "Staff"}
                    </span>
                  </>
                ) : (
                  <>
                    <User className="h-3 w-3 text-[#024d37]" />
                    <span className="font-semibold">{t("nav.portal")}</span>
                  </>
                )}
                <ChevronDown className={`h-2.5 w-2.5 text-muted-foreground transition-transform ${authDropdownOpen ? "rotate-180" : ""}`} />
              </button>

              {authDropdownOpen && (
                <div className="absolute right-0 mt-2 w-64 rounded-2xl border border-border bg-card p-3 shadow-2xl z-[100] space-y-2 font-mono text-xs animate-in fade-in zoom-in-95 duration-150">
                  {currentUser ? (
                    /* LOGGED IN USER MENU */
                    <>
                      <div className="border-b border-border pb-2 px-1">
                        <div className="font-sans font-bold text-foreground text-sm">{currentUser.name}</div>
                        <div className="text-[11px] text-muted-foreground truncate">{currentUser.email}</div>
                        <div className="text-[11px] text-[#024d37] font-semibold mt-0.5">
                          {currentUser.company || currentUser.department}
                        </div>
                      </div>

                      <div className="space-y-1">
                        <Link
                          href={portalHref}
                          onClick={() => setAuthDropdownOpen(false)}
                          className="flex items-center justify-between rounded-xl border border-border bg-muted p-2.5 hover:border-[#024d37] hover:bg-[#024d37]/10 transition-colors text-foreground"
                        >
                          <div className="flex items-center gap-2">
                            <Layers className="h-4 w-4 text-[#024d37]" />
                            <span className="font-sans font-bold text-xs">
                              {isClient ? t("nav.client_portal") : t("nav.admin_portal")}
                            </span>
                          </div>
                          <ArrowRight className="h-3.5 w-3.5 text-[#024d37]" />
                        </Link>
                      </div>

                      <div className="border-t border-border pt-1">
                        <button
                          onClick={handleLogout}
                          className="w-full flex items-center justify-between rounded-lg px-2 py-1.5 text-xs text-destructive hover:bg-destructive/10 transition-colors cursor-pointer"
                        >
                          <span>{t("nav.signout")}</span>
                          <LogOut className="h-3.5 w-3.5" />
                        </button>
                      </div>
                    </>
                  ) : (
                    /* GUEST ACCESS OPTIONS */
                    <>
                      <div className="px-2 py-1 text-[10px] uppercase text-muted-foreground font-semibold">
                        // SECURE PORTAL GATEWAY
                      </div>

                      <div className="space-y-1.5 font-sans">
                        <Link
                          href="/login"
                          onClick={() => setAuthDropdownOpen(false)}
                          className="flex items-center gap-2.5 rounded-xl border border-border bg-muted/60 p-2.5 hover:border-[#024d37] hover:bg-muted transition-colors text-foreground"
                        >
                          <LogIn className="h-4 w-4 text-[#024d37]" />
                          <div>
                            <div className="font-bold text-xs">{t("nav.signin")}</div>
                            <div className="text-[10px] text-muted-foreground font-mono">Client & Staff Access</div>
                          </div>
                        </Link>

                        <Link
                          href="/register"
                          onClick={() => setAuthDropdownOpen(false)}
                          className="flex items-center gap-2.5 rounded-xl border border-[#024d37]/30 bg-[#024d37]/10 p-2.5 hover:bg-[#024d37]/20 transition-colors text-foreground"
                        >
                          <UserPlus className="h-4 w-4 text-[#024d37]" />
                          <div>
                            <div className="font-bold text-xs text-[#024d37]">{t("nav.onboarding")}</div>
                            <div className="text-[10px] text-muted-foreground font-mono">Register Organization & Scope</div>
                          </div>
                        </Link>
                      </div>
                    </>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* 2. MAIN HEADER (Spacious Brand Logo, Navigation Links, Primary CTA) */}
      <div className="w-full border-b border-border/80 bg-background/90 backdrop-blur-md">
        <div className="mx-auto flex h-20 max-w-[1440px] items-center justify-between px-4 sm:px-8">
          {/* Brand: LARGE, CLEAN, PROMINENT LOGO MARK */}
          <Link 
            href="/" 
            aria-label="AetherSoft Innovations Home"
            className="flex items-center transition-transform hover:scale-105 py-1 focus:outline-none"
          >
            <div className="relative h-12 sm:h-14 md:h-16 w-40 sm:w-48 md:w-56 flex items-center">
              <Image
                src={siteSettings?.logo_url || "/assets/logo/logo.png"}
                alt={siteSettings?.company_name || "AetherSoft Innovations"}
                fill
                className="object-contain object-left"
                priority
              />
            </div>
          </Link>

          {/* Spacious Desktop Nav Items */}
          <nav className="hidden items-center lg:flex">
            <div className="flex items-center gap-1.5 rounded-full border border-border bg-card/80 px-4 py-2 text-sm font-medium shadow-xs">
              {navItems.map((link) => {
                const isActive = pathname === link.href;
                return (
                  <Link
                    key={link.name}
                    href={link.href}
                    className={`rounded-full px-4 py-1.5 transition-all text-[14px] ${
                      isActive
                        ? "bg-[#024d37] text-white font-bold shadow-xs"
                        : "text-muted-foreground hover:text-foreground hover:bg-muted/60"
                    }`}
                  >
                    {link.name}
                  </Link>
                );
              })}
            </div>
          </nav>

          {/* Right Action CTA Button */}
          <div className="hidden items-center gap-3 md:flex">
            <ShinyButton href="/contact" size="md" showArrow>
              {t("nav.quote")}
            </ShinyButton>
          </div>

          {/* Mobile Hamburger Menu Toggle */}
          <div className="flex items-center gap-2 md:hidden">
            <button
              onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
              aria-label="Toggle menu"
              className="rounded-xl border border-border bg-card p-2.5 text-muted-foreground hover:text-foreground cursor-pointer"
            >
              {mobileMenuOpen ? <X className="h-6 w-6" /> : <Menu className="h-6 w-6" />}
            </button>
          </div>
        </div>
      </div>

      {/* 3. MOBILE MENU DRAWER */}
      {mobileMenuOpen && (
        <div className="border-b border-border bg-background p-5 md:hidden shadow-2xl">
          <nav className="flex flex-col space-y-2.5 font-sans text-base">
            {navItems.map((link) => (
              <Link
                key={link.name}
                href={link.href}
                onClick={() => setMobileMenuOpen(false)}
                className="flex items-center justify-between rounded-xl p-2.5 text-muted-foreground hover:bg-muted hover:text-foreground font-medium"
              >
                <span>{link.name}</span>
                <ArrowRight className="h-4 w-4" />
              </Link>
            ))}

            <div className="pt-3 border-t border-border flex flex-col gap-2.5">
              {currentUser ? (
                <>
                  <Link
                    href={portalHref}
                    onClick={() => setMobileMenuOpen(false)}
                    className="flex items-center justify-center gap-2 rounded-xl border border-border bg-muted py-3 text-sm font-bold text-foreground"
                  >
                    {isClient ? t("nav.client_portal") : t("nav.admin_portal")}
                  </Link>
                  <button
                    onClick={handleLogout}
                    className="flex items-center justify-center gap-2 rounded-xl border border-destructive/30 bg-destructive/10 py-2.5 text-sm font-bold text-destructive"
                  >
                    {t("nav.signout")}
                  </button>
                </>
              ) : (
                <div className="grid grid-cols-2 gap-2.5 font-sans">
                  <Link
                    href="/login"
                    onClick={() => setMobileMenuOpen(false)}
                    className="flex items-center justify-center gap-1.5 rounded-xl border border-border bg-card py-2.5 text-sm font-bold text-foreground"
                  >
                    {t("nav.signin")}
                  </Link>
                  <Link
                    href="/register"
                    onClick={() => setMobileMenuOpen(false)}
                    className="flex items-center justify-center gap-1.5 rounded-xl bg-[#024d37] text-white py-2.5 text-sm font-bold"
                  >
                    {t("nav.onboarding")}
                  </Link>
                </div>
              )}
              <ShinyButton href="/contact" className="w-full justify-center">
                {t("nav.quote")}
              </ShinyButton>
            </div>
          </nav>
        </div>
      )}
    </header>
  );
}
