"use client";
import { useState, useEffect, useRef } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Menu, X, ChevronDown, Users, MapPin, Award } from "lucide-react";
import RequestQuoteModal from "@/components/RequestQuoteModal";
import RegionsDropdown from "@/components/regions/RegionsDropdown";
import LanguageSwitcher from "@/components/LanguageSwitcher";
import Link from "next/link";
import Image from "next/image";
import { usePathname } from "next/navigation";
import { useTranslations } from "next-intl";

const NAV_KEYS = ["about", "services", "technologies", "projects", "training", "clients", "contact", "news"] as const;
type NavKey = (typeof NAV_KEYS)[number];

const resourceLinkDefs = [
  { key: "inspectors" as const, href: "/inspectors", icon: Users },
  { key: "trackRequest" as const, href: "/requests/track", icon: MapPin },
  { key: "verifyCertificate" as const, href: "/certificates/verify", icon: Award },
];

const getNavHref = (link: NavKey, pathname: string) => {
  if (link === "about") return "/about";
  if (link === "services") return "/services";
  if (link === "technologies") return "/technologies";
  if (link === "projects") return "/projects";
  if (link === "training") return "/training";
  if (link === "clients") return "/clients";
  if (link === "news") return "/news";
  if (link === "contact") return "/contact";
  // if (link === "home") return "/";
  // On sub-pages, link back to home sections
  if (pathname !== "/") return `/#${link}`;
  return `#${link}`;
};

interface NavbarProps {
  logoLightUrl?: string;
  logoDarkUrl?: string;
}

const Navbar = ({ logoLightUrl, logoDarkUrl }: NavbarProps) => {
  const t = useTranslations("nav");
  const [isScrolled, setIsScrolled] = useState(false);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [quoteOpen, setQuoteOpen] = useState(false);
  const [resourcesOpen, setResourcesOpen] = useState(false);
  const [mobileResourcesOpen, setMobileResourcesOpen] = useState(false);
  const resourcesRef = useRef<HTMLDivElement>(null);
  const pathname = usePathname();

  useEffect(() => {
    const handleScroll = () => setIsScrolled(window.scrollY > 50);
    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  // Close resources dropdown on outside click
  useEffect(() => {
    const handleClick = (e: MouseEvent) => {
      if (resourcesRef.current && !resourcesRef.current.contains(e.target as Node)) {
        setResourcesOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClick);
    return () => document.removeEventListener("mousedown", handleClick);
  }, []);

  const renderNavLink = (key: NavKey, className: string, onClick?: () => void) => {
    const href = getNavHref(key, pathname);
    const label = t(key);
    if (href.startsWith("/") && !href.startsWith("/#")) {
      return (
        <Link key={key} href={href} className={className} onClick={onClick}>
          {label}
        </Link>
      );
    }
    return (
      <a key={key} href={href} className={className} onClick={onClick}>
        {label}
      </a>
    );
  };

  return (
    <nav
      className={`fixed w-full z-50 transition-all duration-500 ${isScrolled
          ? "bg-card shadow-[0_4px_30px_rgba(5,46,116,0.1)] py-2"
          : "bg-transparent py-5"
        }`}
    >
      <div className="petro-container justify-between flex items-center px-4 sm:px-6">

        <Link href="/" className="shrink-0">
          <Image src={isScrolled ? (logoDarkUrl ?? "/logo.png") : (logoLightUrl ?? "/logo-white.png")} alt="Petro-Base Group" width={120} height={48} className="h-[72px] xl:h-[96px] w-auto transition-all duration-500" style={{ width: "auto" }} />
        </Link>


        <div className="hidden md:flex flex-1 justify-end items-center gap-2 lg:gap-3 xl:gap-5 ml-6 lg:ml-12">
          {NAV_KEYS.map((key) =>
            renderNavLink(
              key,
              `text-xs lg:text-sm font-medium transition-colors duration-300 hover:text-accent ${isScrolled ? "text-foreground" : "text-primary-foreground/90"
              }`
            )
          )}

          {/* Regions dropdown */}
          <RegionsDropdown isScrolled={isScrolled} />

          {/* Resources dropdown */}
          <div ref={resourcesRef} className="relative">
            <button
              onMouseEnter={() => setResourcesOpen(true)}
              onMouseLeave={() => setResourcesOpen(false)}
              className={`flex items-center gap-1 text-xs lg:text-sm font-medium transition-colors duration-300 hover:text-accent ${isScrolled ? "text-foreground" : "text-primary-foreground/90"
                }`}
            >
              {t("resources")}
              <ChevronDown className={`w-3.5 h-3.5 transition-transform duration-200 ${resourcesOpen ? "rotate-180" : ""}`} />
            </button>

            <AnimatePresence>
              {resourcesOpen && (
                <motion.div
                  initial={{ opacity: 0, y: 6 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: 6 }}
                  transition={{ duration: 0.15 }}
                  className="absolute top-full right-0 w-64 bg-card border border-border rounded-xl shadow-lg overflow-hidden z-50"
                >
                  {resourceLinkDefs.map(({ key, href, icon: Icon }) => (
                    <Link
                      key={key}
                      href={href}
                      onMouseEnter={() => setResourcesOpen(true)}
                      onMouseLeave={() => setResourcesOpen(false)}
                      className="flex items-start gap-3 px-4 py-3 hover:bg-secondary transition-colors group"
                    >
                      <div className="w-8 h-8 rounded-lg bg-accent/10 flex items-center justify-center shrink-0 mt-0.5 group-hover:bg-accent/20 transition-colors">
                        <Icon className="w-4 h-4 text-accent" />
                      </div>
                      <div>
                        <p className="text-sm font-semibold text-foreground">{t(key)}</p>
                        <p className="text-xs text-muted-foreground">{t(`${key}Desc`)}</p>
                      </div>
                    </Link>
                  ))}
                </motion.div>
              )}
            </AnimatePresence>
          </div>

          <button onClick={() => setQuoteOpen(true)} className="petro-btn-gold py-1.5 px-4 lg:py-2.5 lg:px-6 text-[10px] lg:text-[11px]">
            {t("requestQuote")}
          </button>

          <LanguageSwitcher light={!isScrolled} />
        </div>

        <button
          className="md:hidden"
          onClick={() => setMobileMenuOpen(true)}
          aria-label="Open menu"
        >
          <Menu
            className={isScrolled ? "text-primary" : "text-primary-foreground"}
            size={24}
          />
        </button>
      </div>

      <AnimatePresence>
        {mobileMenuOpen && (
          <>
            {/* Backdrop */}
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.25 }}
              className="lg:hidden fixed inset-0 bg-black/50 z-40"
              onClick={() => setMobileMenuOpen(false)}
            />

            {/* Sidebar */}
            <motion.div
              initial={{ x: "-100%" }}
              animate={{ x: 0 }}
              exit={{ x: "-100%" }}
              transition={{ type: "tween", duration: 0.3, ease: "easeInOut" }}
              className="lg:hidden fixed top-0 left-0 h-full w-72 bg-card z-50 flex flex-col shadow-2xl"
            >
              {/* Sidebar header */}
              <div className="flex items-center justify-between px-5 py-4 border-b border-border">
                <Link href="/" onClick={() => setMobileMenuOpen(false)}>
                  <Image
                    src={logoDarkUrl ?? "/logo.png"}
                    alt="Petro-Base Group"
                    width={100}
                    height={40}
                    className="h-12 w-auto"
                    style={{ width: "auto" }}
                  />
                </Link>
                <button
                  onClick={() => setMobileMenuOpen(false)}
                  aria-label="Close menu"
                  className="p-1 rounded-sm hover:bg-secondary transition-colors"
                >
                  <X className="text-primary" size={20} />
                </button>
              </div>

              {/* Nav links */}
              <nav className="flex flex-col gap-1 px-3 py-5 flex-1 overflow-y-auto">
                {NAV_KEYS.map((key) =>
                  renderNavLink(
                    key,
                    "flex items-center px-4 py-3 text-sm font-semibold text-foreground hover:text-accent hover:bg-secondary rounded-sm transition-colors",
                    () => setMobileMenuOpen(false)
                  )
                )}

                {/* Regions section */}
                <div>
                  <RegionsDropdown isScrolled={true} isMobile={true} />
                </div>

                {/* Resources section */}
                <div>
                  <button
                    onClick={() => setMobileResourcesOpen((o) => !o)}
                    className="flex items-center justify-between w-full px-4 py-3 text-sm font-semibold text-foreground hover:text-accent hover:bg-secondary rounded-sm transition-colors"
                  >
                    {t("resources")}
                    <ChevronDown className={`w-4 h-4 transition-transform duration-200 ${mobileResourcesOpen ? "rotate-180" : ""}`} />
                  </button>
                  <AnimatePresence>
                    {mobileResourcesOpen && (
                      <motion.div
                        initial={{ height: 0, opacity: 0 }}
                        animate={{ height: "auto", opacity: 1 }}
                        exit={{ height: 0, opacity: 0 }}
                        transition={{ duration: 0.2 }}
                        className="overflow-hidden"
                      >
                        {resourceLinkDefs.map(({ key, href, icon: Icon }) => (
                          <Link
                            key={key}
                            href={href}
                            onClick={() => { setMobileMenuOpen(false); setMobileResourcesOpen(false); }}
                            className="flex items-center gap-3 pl-8 pr-4 py-2.5 text-sm text-muted-foreground hover:text-accent hover:bg-secondary rounded-sm transition-colors"
                          >
                            <Icon className="w-4 h-4 shrink-0" />
                            {t(key)}
                          </Link>
                        ))}
                      </motion.div>
                    )}
                  </AnimatePresence>
                </div>
              </nav>

              {/* CTA */}
              <div className="px-5 py-5 border-t border-border space-y-3">
                <button
                  onClick={() => { setMobileMenuOpen(false); setQuoteOpen(true); }}
                  className="petro-btn-gold w-full text-[11px]"
                >
                  {t("requestQuote")}
                </button>
                <div className="flex justify-center">
                  <LanguageSwitcher light={false} dropUp />
                </div>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
      <RequestQuoteModal open={quoteOpen} onOpenChange={setQuoteOpen} />
    </nav>
  );
};

export default Navbar;
