import React, { useContext, useEffect, useMemo, useRef, useState } from "react";
import { ArrowUp } from "lucide-react";
import { AuthContext } from "@/contexts/AuthContext";
import { useScroll } from "@/contexts/DashboardScrollContext";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

const ALL_SECTIONS = [
  { id: "stats", label: "Overview", permission: "dashboard:stats" },
  { id: "financial", label: "Financial", permission: "dashboard:financial" },
  { id: "sales", label: "Sales", permission: "dashboard:sales" },
  { id: "feed", label: "Events", permission: "dashboard:feed" },
  { id: "operations-metrics", label: "Operations", permission: "dashboard:operations" },
  { id: "payroll-metrics", label: "Payroll", permission: "dashboard:payroll" },
  { id: "products", label: "Products", permission: "dashboard:products" },
  { id: "campaigns", label: "Klaviyo", permission: "dashboard:campaigns" },
  { id: "analytics", label: "Analytics", permission: "dashboard:analytics" },
  { id: "user-behavior", label: "Behavior", permission: "dashboard:user_behavior" },
  { id: "meta-campaigns", label: "Meta Ads", permission: "dashboard:meta_campaigns" },
  { id: "typeform", label: "Surveys", permission: "dashboard:typeform" },
  { id: "customer-service", label: "Support", permission: "dashboard:customer_service" },
];

const Navigation = () => {
  const [activeSection, setActiveSection] = useState(null);
  const { isStuck, scrollContainerRef, scrollToSection } = useScroll();
  const { user } = useContext(AuthContext);
  const navRef = useRef(null);
  const buttonRefs = useRef({});

  const sections = useMemo(() => {
    if (!user) return [];
    if (user.is_admin) return ALL_SECTIONS;
    return ALL_SECTIONS.filter((section) =>
      user.permissions?.includes(section.permission)
    );
  }, [user]);

  useEffect(() => {
    const container = scrollContainerRef.current;
    if (!container || !sections.length) return undefined;

    const updateActiveSection = () => {
      const containerTop = container.getBoundingClientRect().top;
      let current = sections[0]?.id ?? null;

      sections.forEach(({ id }) => {
        const element = document.getElementById(id);
        if (element && element.getBoundingClientRect().top - containerTop <= 140) {
          current = id;
        }
      });

      setActiveSection(current);
    };

    container.addEventListener("scroll", updateActiveSection, { passive: true });
    updateActiveSection();
    return () => container.removeEventListener("scroll", updateActiveSection);
  }, [scrollContainerRef, sections]);

  useEffect(() => {
    const activeButton = activeSection && buttonRefs.current[activeSection];
    activeButton?.scrollIntoView({
      behavior: "smooth",
      block: "nearest",
      inline: "center",
    });
  }, [activeSection]);

  const scrollToTop = () => {
    scrollContainerRef.current?.scrollTo({ top: 0, behavior: "smooth" });
  };

  return (
    <div
      className={cn(
        "sticky top-0 z-40 px-3 sm:px-4 lg:px-5",
        isStuck && "bg-[#f8f7f5]/90 backdrop-blur-lg"
      )}
    >
      <div
        className={cn(
          "flex min-w-0 items-center border-b border-[#eceae5] transition-shadow",
          isStuck && "shadow-[0_8px_16px_-16px_rgba(43,41,37,0.35)]"
        )}
      >
        <div
          ref={navRef}
          className="no-scrollbar flex min-w-0 flex-1 gap-0.5 overflow-x-auto py-2"
        >
          {sections.map(({ id, label }) => (
            <Button
              key={id}
              ref={(element) => {
                buttonRefs.current[id] = element;
              }}
              variant="ghost"
              size="sm"
              className={cn(
                "h-7 shrink-0 rounded-full px-3 text-xs font-medium text-[#7c7870]",
                "hover:bg-[#f0eeea] hover:text-[#2b2925]",
                activeSection === id &&
                  "bg-[#2b2925] text-white hover:bg-[#2b2925] hover:text-white"
              )}
              onClick={() => scrollToSection(id)}
            >
              {label}
            </Button>
          ))}
        </div>

        {isStuck && (
          <Button
            variant="ghost"
            size="icon"
            className="ml-2 h-7 w-7 shrink-0"
            onClick={scrollToTop}
            aria-label="Scroll to top"
          >
            <ArrowUp className="h-3.5 w-3.5" />
          </Button>
        )}
      </div>
    </div>
  );
};

export default Navigation;
