import { useState, useEffect, useRef } from "react";
import { Link, useLocation } from "react-router-dom";
import { Menu, X, ChevronDown, LogIn, Briefcase, Share2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import chatskuLogo from "@/assets/chatsku-logo.png";
import { problems, severityColors, severityTextColors } from "@/data/problems";

const Navbar = () => {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const [problemsOpen, setProblemsMobileOpen] = useState(false);
  const [partnersOpen, setPartnersMobileOpen] = useState(false);
  const [megaOpen, setMegaOpen] = useState(false);
  const [partnersMenuOpen, setPartnersMenuOpen] = useState(false);
  const megaTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
  const partnersTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
  const location = useLocation();

  const isProblemsActive = location.pathname.startsWith("/problems");
  const isPartnersActive = location.pathname.startsWith("/partners");

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

  useEffect(() => {
    setMenuOpen(false);
    setProblemsMobileOpen(false);
    setPartnersMobileOpen(false);
    setMegaOpen(false);
    setPartnersMenuOpen(false);
  }, [location.pathname]);

  const handleMegaEnter = () => {
    if (megaTimeout.current) clearTimeout(megaTimeout.current);
    setMegaOpen(true);
  };

  const handleMegaLeave = () => {
    megaTimeout.current = setTimeout(() => setMegaOpen(false), 200);
  };

  const handlePartnersEnter = () => {
    if (partnersTimeout.current) clearTimeout(partnersTimeout.current);
    setPartnersMenuOpen(true);
  };

  const handlePartnersLeave = () => {
    partnersTimeout.current = setTimeout(() => setPartnersMenuOpen(false), 200);
  };

  const navLinks = [
    { label: "Demo", to: "/demo" },
    { label: "Features", to: "/features" },
    { label: "Pricing", to: "/pricing" },
    { label: "FAQ", to: "/faq" },
  ];

  return (
    <header
      className={cn(
        "fixed top-0 left-0 right-0 z-50 transition-all duration-300",
        scrolled
          ? "bg-background border-b border-border shadow-lg shadow-background/20"
          : "bg-background"
      )}
    >
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex items-center justify-between h-16">
          {/* Logo */}
          <Link to="/" className="group hover:opacity-90 transition-opacity">
            <img src={chatskuLogo} alt="ChatSKU" className="h-8" />
          </Link>

          {/* Desktop Nav */}
          <nav className="hidden md:flex items-center gap-8">
            <Link
              to="/demo"
              className={cn(
                "text-sm font-medium transition-colors hover:text-primary",
                location.pathname === "/demo" ? "text-primary" : "text-muted-foreground"
              )}
            >
              Demo
            </Link>

            <Link
              to="/features"
              className={cn(
                "text-sm font-medium transition-colors hover:text-primary",
                location.pathname === "/features" ? "text-primary" : "text-muted-foreground"
              )}
            >
              Features
            </Link>

            {/* Problems mega-menu trigger */}
            <div
              className="relative"
              onMouseEnter={handleMegaEnter}
              onMouseLeave={handleMegaLeave}
            >
              <Link
                to="/problems"
                className={cn(
                  "text-sm font-medium transition-colors hover:text-primary inline-flex items-center gap-1",
                  isProblemsActive ? "text-primary" : "text-muted-foreground"
                )}
              >
                Problems
                <ChevronDown className={cn("w-3.5 h-3.5 transition-transform", megaOpen && "rotate-180")} />
              </Link>

              {/* Mega dropdown */}
              <div
                className={cn(
                  "absolute top-full left-1/2 -translate-x-1/2 pt-2 transition-all duration-150",
                  megaOpen ? "opacity-100 visible translate-y-0" : "opacity-0 invisible -translate-y-1"
                )}
              >
                <div className="w-[520px] rounded-lg border-t-2 border-t-primary bg-secondary shadow-xl shadow-background/40 p-6">
                  <div className="grid grid-cols-2 gap-8">
                    {/* Left column */}
                    <div>
                      <div className="text-[10px] font-bold text-primary uppercase tracking-[0.2em] mb-3">
                        The 6 Revenue Gaps
                      </div>
                      <div className="space-y-2">
                        {problems.map((p) => (
                          <Link
                            key={p.slug}
                            to={`/problems/${p.slug}`}
                            className="flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors py-1"
                          >
                            <div className={`w-1.5 h-1.5 rounded-full flex-shrink-0 ${severityColors[p.severity]}`} />
                            {p.name}
                          </Link>
                        ))}
                      </div>
                    </div>

                    {/* Right column */}
                    <div>
                      <div className="text-[10px] font-bold text-primary uppercase tracking-[0.2em] mb-3">
                        Not Sure Where to Start?
                      </div>
                      <p className="text-sm text-muted-foreground leading-relaxed mb-4">
                        Most B2B catalogs have at least three of these problems working against them at the same time.
                      </p>
                      <Link
                        to="/problems"
                        className="text-sm font-semibold text-primary hover:text-teal-glow transition-colors inline-block mb-3"
                      >
                        See all six problems
                      </Link>
                      <div>
                        <Button
                          asChild
                          variant="outline"
                          size="sm"
                          className="border-border hover:border-primary/50 hover:bg-primary/5 text-xs"
                        >
                          <Link to="/demo">Try Live Demo</Link>
                        </Button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {navLinks.filter(l => !["Demo", "Features"].includes(l.label)).map((link) => (
              <Link
                key={link.to}
                to={link.to}
                className={cn(
                  "text-sm font-medium transition-colors hover:text-primary",
                  location.pathname === link.to
                    ? "text-primary"
                    : "text-muted-foreground"
                )}
              >
                {link.label}
              </Link>
            ))}

            <Link
              to="/blog"
              className={cn(
                "text-sm font-medium transition-colors hover:text-primary",
                location.pathname.startsWith("/blog") ? "text-primary" : "text-muted-foreground"
              )}
            >
              Blog
            </Link>

            {/* Partners dropdown */}
            <div
              className="relative"
              onMouseEnter={handlePartnersEnter}
              onMouseLeave={handlePartnersLeave}
            >
              <button
                className={cn(
                  "text-sm font-medium transition-colors hover:text-primary inline-flex items-center gap-1",
                  isPartnersActive ? "text-primary" : "text-muted-foreground"
                )}
              >
                Partners
                <ChevronDown className={cn("w-3.5 h-3.5 transition-transform", partnersMenuOpen && "rotate-180")} />
              </button>
              {isPartnersActive && (
                <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary rounded-full" />
              )}

              <div
                className={cn(
                  "absolute top-full right-0 pt-2 transition-all duration-150",
                  partnersMenuOpen ? "opacity-100 visible translate-y-0" : "opacity-0 invisible -translate-y-1"
                )}
              >
                <div className="w-[280px] rounded-lg bg-[#161B22] border border-[#21262D] shadow-lg p-2">
                  <Link
                    to="/partners/agency"
                    className="flex items-start gap-3 rounded-md px-3 py-2.5 hover:bg-[#1C2128] transition-colors"
                  >
                    <Briefcase className="w-4 h-4 text-[#00C9A7] mt-0.5 shrink-0" />
                    <div>
                      <div className="text-sm font-medium text-white">Agency Partners</div>
                      <div className="text-xs text-[#94A3B8]">For agencies serving B2B clients</div>
                    </div>
                  </Link>
                  <Link
                    to="/partners/affiliate"
                    className="flex items-start gap-3 rounded-md px-3 py-2.5 hover:bg-[#1C2128] transition-colors"
                  >
                    <Share2 className="w-4 h-4 text-[#00C9A7] mt-0.5 shrink-0" />
                    <div>
                      <div className="text-sm font-medium text-white">Affiliates</div>
                      <div className="text-xs text-[#94A3B8]">For creators and consultants with B2B audiences</div>
                    </div>
                  </Link>
                </div>
              </div>
            </div>
          </nav>

          {/* Desktop CTA */}
          <div className="hidden md:flex items-center gap-3">
            <Link
              to="/login"
              className="text-muted-foreground hover:text-primary transition-colors"
              aria-label="Log in"
            >
              <LogIn className="w-5 h-5" />
            </Link>
            <Button
              asChild
              className="bg-primary text-primary-foreground hover:bg-teal-glow font-semibold px-5 glow-teal-sm transition-all duration-200"
            >
              <Link to="/signup">Start Free</Link>
            </Button>
          </div>

          {/* Mobile hamburger */}
          <button
            className="md:hidden p-2 rounded-md text-muted-foreground hover:text-foreground transition-colors"
            onClick={() => setMenuOpen(!menuOpen)}
            aria-label="Toggle menu"
          >
            {menuOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
          </button>
        </div>
      </div>

      {/* Mobile Menu */}
      <div
        className={cn(
          "md:hidden overflow-hidden transition-all duration-300 ease-in-out border-b border-border",
          menuOpen
            ? "max-h-[500px] bg-background backdrop-blur-md"
            : "max-h-0"
        )}
      >
        <nav className="flex flex-col px-4 py-4 gap-1">
          <Link
            to="/demo"
            className={cn(
              "px-3 py-2.5 rounded-md text-sm font-medium transition-colors",
              location.pathname === "/demo"
                ? "text-primary bg-primary/10"
                : "text-muted-foreground hover:text-foreground hover:bg-secondary"
            )}
          >
            Demo
          </Link>

          <Link
            to="/features"
            className={cn(
              "px-3 py-2.5 rounded-md text-sm font-medium transition-colors",
              location.pathname === "/features"
                ? "text-primary bg-primary/10"
                : "text-muted-foreground hover:text-foreground hover:bg-secondary"
            )}
          >
            Features
          </Link>

          {/* Problems accordion */}
          <button
            onClick={() => setProblemsMobileOpen(!problemsOpen)}
            className={cn(
              "px-3 py-2.5 rounded-md text-sm font-medium transition-colors flex items-center justify-between w-full text-left",
              isProblemsActive
                ? "text-primary bg-primary/10"
                : "text-muted-foreground hover:text-foreground hover:bg-secondary"
            )}
          >
            Problems
            <ChevronDown className={cn("w-4 h-4 transition-transform", problemsOpen && "rotate-180")} />
          </button>
          <div
            className={cn(
              "overflow-hidden transition-all duration-200",
              problemsOpen ? "max-h-[300px]" : "max-h-0"
            )}
          >
            <div className="pl-6 space-y-0.5 pb-1">
              {problems.map((p) => (
                <Link
                  key={p.slug}
                  to={`/problems/${p.slug}`}
                  className={cn(
                    "flex items-center gap-2 px-3 py-2 rounded-md text-sm transition-colors",
                    location.pathname === `/problems/${p.slug}`
                      ? "text-primary bg-primary/10"
                      : "text-muted-foreground hover:text-foreground hover:bg-secondary"
                  )}
                >
                  <div className={`w-1.5 h-1.5 rounded-full flex-shrink-0 ${severityColors[p.severity]}`} />
                  {p.name}
                </Link>
              ))}
            </div>
          </div>

          {navLinks.filter(l => !["Demo", "Features"].includes(l.label)).map((link) => (
            <Link
              key={link.to}
              to={link.to}
              className={cn(
                "px-3 py-2.5 rounded-md text-sm font-medium transition-colors",
                location.pathname === link.to
                  ? "text-primary bg-primary/10"
                  : "text-muted-foreground hover:text-foreground hover:bg-secondary"
              )}
            >
              {link.label}
            </Link>
          ))}

          <Link
            to="/blog"
            className={cn(
              "px-3 py-2.5 rounded-md text-sm font-medium transition-colors",
              location.pathname.startsWith("/blog")
                ? "text-primary bg-primary/10"
                : "text-muted-foreground hover:text-foreground hover:bg-secondary"
            )}
          >
            Blog
          </Link>

          {/* Partners accordion (mobile) */}
          <button
            onClick={() => setPartnersMobileOpen(!partnersOpen)}
            className={cn(
              "px-3 py-2.5 rounded-md text-sm font-medium transition-colors flex items-center justify-between w-full text-left",
              isPartnersActive
                ? "text-primary bg-primary/10"
                : "text-muted-foreground hover:text-foreground hover:bg-secondary"
            )}
          >
            Partners
            <ChevronDown className={cn("w-4 h-4 transition-transform", partnersOpen && "rotate-180")} />
          </button>
          <div
            className={cn(
              "overflow-hidden transition-all duration-200",
              partnersOpen ? "max-h-[200px]" : "max-h-0"
            )}
          >
            <div className="pl-6 space-y-0.5 pb-1">
              <Link
                to="/partners/agency"
                className={cn(
                  "flex items-center gap-2 px-3 py-2 rounded-md text-sm transition-colors",
                  location.pathname === "/partners/agency"
                    ? "text-primary bg-primary/10"
                    : "text-muted-foreground hover:text-foreground hover:bg-secondary"
                )}
              >
                <Briefcase className="w-3.5 h-3.5 text-[#00C9A7]" />
                Agency Partners
              </Link>
              <Link
                to="/partners/affiliate"
                className={cn(
                  "flex items-center gap-2 px-3 py-2 rounded-md text-sm transition-colors",
                  location.pathname === "/partners/affiliate"
                    ? "text-primary bg-primary/10"
                    : "text-muted-foreground hover:text-foreground hover:bg-secondary"
                )}
              >
                <Share2 className="w-3.5 h-3.5 text-[#00C9A7]" />
                Affiliates
              </Link>
            </div>
          </div>
          <div className="mt-3 pt-3 border-t border-border flex flex-col gap-2">
            <Link
              to="/login"
              className={cn(
                "px-3 py-2.5 rounded-md text-sm font-medium transition-colors flex items-center gap-2",
                location.pathname === "/login"
                  ? "text-primary bg-primary/10"
                  : "text-muted-foreground hover:text-foreground hover:bg-secondary"
              )}
            >
              <LogIn className="w-4 h-4" /> Log In
            </Link>
            <Button asChild className="w-full bg-primary text-primary-foreground font-semibold">
              <Link to="/signup">Start Free</Link>
            </Button>
          </div>
        </nav>
      </div>
    </header>
  );
};

export default Navbar;
