import { useEffect, useMemo, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Menu, X } from "lucide-react";
import AuthDialogs from "./AuthDialogs";
import BrokerConnectDialog from "./BrokerConnectDialog";
import { apiRequest, getQueryFn } from "@/lib/queryClient";
import type { User } from "@shared/schema";
import { useLocation } from "wouter";

type SessionUser = Pick<User, "id" | "username">;

export default function Navigation() {
  const [isScrolled, setIsScrolled] = useState(false);
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const [activeSection, setActiveSection] = useState<string | null>(null);
  const pendingHashRef = useRef<string | null>(null);
  const sectionIds = useMemo(() => ["philosophy", "strategies", "how-it-works"], []);
  const [location, navigate] = useLocation();
  const queryClient = useQueryClient();

  const { data: sessionUser } = useQuery<SessionUser | null>({
    queryKey: ["/me"],
    queryFn: getQueryFn<SessionUser | null>({ on401: "returnNull" }),
  });

  const logoutMutation = useMutation({
    mutationFn: async () => {
      await apiRequest("POST", "/logout");
    },
    onSuccess: () => {
      queryClient.setQueryData(["/me"], null);
      queryClient.removeQueries({ queryKey: ["/broker/status"] });
      window.location.assign("/");
    },
  });

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

  const smoothScroll = (id?: string) => {
    if (!id) {
      window.scrollTo({ top: 0, behavior: "smooth" });
      return;
    }
    const el = document.getElementById(id);
    if (el) {
      try {
        el.scrollIntoView({ behavior: "smooth", block: "start" });
      } catch {
        window.scrollTo({ top: el.offsetTop - 80, behavior: "smooth" });
      }
    }
  };

  const navLinks = useMemo(
    () => [
      { label: "Home", href: "#" },
      { label: "Portfolio", href: "/portfolio", newTab: true },
      { label: "Strategies", href: "#strategies" },
      { label: "How It Works", href: "#how-it-works" },
      { label: "Support", href: "/support" },
    ],
    [],
  );

  const handleNavClick = (href: string) => {
    setIsMobileMenuOpen(false);
    const hash = href.startsWith("#") ? href.slice(1) : "";
    if (href.startsWith("/") && !href.startsWith("#")) {
      navigate(href);
      return;
    }
    if (location === "/") {
      smoothScroll(hash);
    } else {
      pendingHashRef.current = hash;
      navigate("/");
    }
  };

  useEffect(() => {
    // after navigating home, scroll to pending hash or current hash
    if (location !== "/") return;
    const hash = pendingHashRef.current || window.location.hash.replace("#", "");
    if (!hash) return;
    const attempt = (tries: number) => {
      const el = document.getElementById(hash);
      if (el) {
        smoothScroll(hash);
        pendingHashRef.current = null;
        return;
      }
      if (tries > 10) return;
      requestAnimationFrame(() => attempt(tries + 1));
    };
    attempt(0);
  }, [location]);

  useEffect(() => {
    if (location !== "/") {
      setActiveSection(null);
      return;
    }
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
      setActiveSection(null);
      return;
    }
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) setActiveSection(entry.target.id);
        });
      },
      { threshold: 0.4 },
    );
    sectionIds.forEach((id) => {
      const el = document.getElementById(id);
      if (el) observer.observe(el);
    });
    return () => observer.disconnect();
  }, [location, sectionIds]);

  const isActiveLink = (href: string) => {
    if (href.startsWith("#")) {
      return location === "/" && activeSection === href.slice(1);
    }
    return location === href || location.startsWith(`${href}/`);
  };

  const LinkItem = ({
    link,
    mobile = false,
  }: {
    link: { label: string; href: string; newTab?: boolean };
    mobile?: boolean;
  }) => (
    <button
      onClick={() => handleNavClick(link.href)}
      className={`group relative text-sm font-medium transition-colors duration-300 ${
        isActiveLink(link.href) ? "text-foreground" : "text-muted-foreground hover:text-foreground"
      } ${mobile ? "w-full py-1.5 text-left text-base" : "whitespace-nowrap"}`}
      data-testid={`link-nav-${link.label.toLowerCase().replace(/\s/g, "-")}`}
    >
      {link.label}
      <span
        className={`pointer-events-none absolute -bottom-1 left-0 h-[2px] w-full origin-left scale-x-0 bg-primary transition-transform duration-300 ${
          isActiveLink(link.href) ? "scale-x-100" : "group-hover:scale-x-100"
        }`}
      />
    </button>
  );

  return (
    <nav
      data-testid="navigation"
      className={`fixed top-0 left-0 right-0 z-50 transition-all duration-500 ${
        isScrolled ? "bg-background/80 backdrop-blur-xl border-b border-border" : "bg-transparent"
      }`}
    >
      <div className="mx-auto max-w-6xl px-4 py-3 sm:px-6 sm:py-4">
        <div className="flex items-center justify-between gap-4">
          <button
            onClick={() => handleNavClick("#")}
            className="text-lg font-bold tracking-tight text-foreground sm:text-xl"
            data-testid="link-logo"
          >
            QuantFortune
          </button>

          <div className="hidden md:flex items-center gap-8">
            {navLinks.map((link) => (
              <LinkItem key={link.label} link={link} />
            ))}
          </div>

          <div className="hidden md:flex items-center gap-3">
            {sessionUser ? (
              <>
                <div className="flex max-w-[11rem] items-center gap-2 rounded-full border border-primary/40 bg-primary/10 px-3 py-1 text-sm font-medium text-primary lg:max-w-[16rem]">
                  <span className="h-2 w-2 rounded-full bg-primary" />
                  <span className="truncate">{sessionUser.username}</span>
                </div>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => logoutMutation.mutate()}
                  disabled={logoutMutation.isPending}
                >
                  {logoutMutation.isPending ? "Logging out..." : "Log out"}
                </Button>
                <BrokerConnectDialog />
              </>
            ) : (
              <AuthDialogs />
            )}
          </div>

          <Button
            variant="ghost"
            size="icon"
            className="shrink-0 text-foreground md:hidden"
            onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
            data-testid="button-mobile-menu"
            aria-label={isMobileMenuOpen ? "Close navigation menu" : "Open navigation menu"}
          >
            {isMobileMenuOpen ? <X className="h-5 w-5" /> : <Menu className="h-5 w-5" />}
          </Button>
        </div>

        {isMobileMenuOpen && (
          <div className="mt-3 rounded-2xl border border-border bg-background/95 px-3 pb-4 pt-4 shadow-xl backdrop-blur-xl md:hidden">
            <div className="flex flex-col gap-4">
              {navLinks.map((link) => (
                <LinkItem key={link.label} link={link} mobile />
              ))}
              <div className="border-t border-border pt-2">
                <div className="flex flex-col gap-3">
                  {sessionUser ? (
                    <>
                      <div className="flex items-center gap-2 rounded-xl border border-primary/40 bg-primary/10 px-3 py-2 text-sm font-medium text-primary">
                        <span className="h-2 w-2 rounded-full bg-primary" />
                        <span className="truncate">{sessionUser.username}</span>
                      </div>
                      <Button
                        variant="outline"
                        onClick={() => {
                          logoutMutation.mutate();
                          setIsMobileMenuOpen(false);
                        }}
                        disabled={logoutMutation.isPending}
                      >
                        {logoutMutation.isPending ? "Logging out..." : "Log out"}
                      </Button>
                      <BrokerConnectDialog layout="mobile" />
                    </>
                  ) : (
                    <AuthDialogs layout="mobile" />
                  )}
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </nav>
  );
}
