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

const Navigation = () => {
  const [activeSections, setActiveSections] = useState([]);
  const { isStuck, scrollContainerRef, scrollToSection } = useScroll();
  const { user } = useContext(AuthContext);
  const buttonRefs = useRef({});
  const scrollContainerRef2 = useRef(null);
  const [shouldAutoScroll, setShouldAutoScroll] = useState(true);
  const lastScrollLeft = useRef(0);
  const lastScrollTop = useRef(0);

  // Define all possible sections with their permission requirements
  const allSections = [
    { id: "stats", label: "Statistics", permission: "dashboard:stats" },
    { id: "realtime", label: "Realtime", permission: "dashboard:realtime" },
    { id: "financial", label: "Financial", permission: "dashboard:financial" },
    { id: "payroll-metrics", label: "Payroll", permission: "dashboard:payroll" },
    { id: "operations-metrics", label: "Operations", permission: "dashboard:operations" },
    { id: "feed", label: "Event Feed", permission: "dashboard:feed" },
    { id: "sales", label: "Sales Chart", permission: "dashboard:sales" },
    { id: "products", label: "Top Products", permission: "dashboard:products" },
    { id: "campaigns", label: "Campaigns", permission: "dashboard:campaigns" },
    { id: "analytics", label: "Analytics", permission: "dashboard:analytics" },
    { id: "user-behavior", label: "User Behavior", permission: "dashboard:user_behavior" },
    { id: "meta-campaigns", label: "Meta Ads", permission: "dashboard:meta_campaigns" },
    { id: "typeform", label: "Customer Surveys", permission: "dashboard:typeform" },
  ];

  // Filter sections based on user permissions
  const baseSections = useMemo(() => {
    if (!user) return [];

    // Admins see all sections
    if (user.is_admin) return allSections;

    // Filter sections based on user permissions
    return allSections.filter(section =>
      user.permissions && user.permissions.includes(section.permission)
    );
  }, [user]);

  const sortSections = (sections) => {
    const isMediumScreen = window.matchMedia(
      "(min-width: 768px) and (max-width: 1023px)"
    ).matches;

    return [...sections].sort((a, b) => {
      const aOrder = a.order
        ? isMediumScreen
          ? a.order.md
          : a.order.default
        : 0;
      const bOrder = b.order
        ? isMediumScreen
          ? b.order.md
          : b.order.default
        : 0;

      if (aOrder && bOrder) {
        return aOrder - bOrder;
      }
      return 0;
    });
  };

  const sections = sortSections(baseSections);

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

  const handleSectionClick = (sectionId, responsiveIds) => {
    scrollToSection(sectionId);
  };

  // Track horizontal scroll position changes
  useEffect(() => {
    const container = scrollContainerRef.current;
    if (!container) return;

    const handleButtonBarScroll = () => {
      if (Math.abs(container.scrollLeft - lastScrollLeft.current) > 5) {
        setShouldAutoScroll(false);
      }
      lastScrollLeft.current = container.scrollLeft;
    };

    container.addEventListener("scroll", handleButtonBarScroll);
    return () => container.removeEventListener("scroll", handleButtonBarScroll);
  }, []);

  // Handle page scroll and active sections
  useEffect(() => {
    const handlePageScroll = (e) => {
      const scrollTop = e?.target?.scrollTop || window.pageYOffset || document.documentElement.scrollTop;

      if (Math.abs(scrollTop - lastScrollTop.current) > 5) {
        setShouldAutoScroll(true);
        lastScrollTop.current = scrollTop;
      } else {
        return;
      }

      const activeIds = [];
      const viewportHeight = window.innerHeight;
      const threshold = viewportHeight * 0.5;
      const container = scrollContainerRef.current;

      sections.forEach((section) => {
        if (section.responsiveIds) {
          const visibleId = section.responsiveIds.find((id) => {
            const element = document.getElementById(id);
            if (!element) return false;
            const style = window.getComputedStyle(element);
            if (style.display === "none") return false;

            if (container) {
              // For container-based scrolling
              const rect = element.getBoundingClientRect();
              const containerRect = container.getBoundingClientRect();
              const relativeTop = rect.top - containerRect.top;
              const relativeBottom = rect.bottom - containerRect.top;
              return (
                relativeTop < containerRect.height - threshold && 
                relativeBottom > threshold
              );
            } else {
              // For window-based scrolling
              const rect = element.getBoundingClientRect();
              return (
                rect.top < viewportHeight - threshold && rect.bottom > threshold
              );
            }
          });

          if (visibleId) {
            activeIds.push(section.id);
          }
        } else {
          const element = document.getElementById(section.id);
          if (element) {
            if (container) {
              // For container-based scrolling
              const rect = element.getBoundingClientRect();
              const containerRect = container.getBoundingClientRect();
              const relativeTop = rect.top - containerRect.top;
              const relativeBottom = rect.bottom - containerRect.top;
              if (
                relativeTop < containerRect.height - threshold && 
                relativeBottom > threshold
              ) {
                activeIds.push(section.id);
              }
            } else {
              // For window-based scrolling
              const rect = element.getBoundingClientRect();
              if (
                rect.top < viewportHeight - threshold &&
                rect.bottom > threshold
              ) {
                activeIds.push(section.id);
              }
            }
          }
        }
      });

      setActiveSections(activeIds);

      if (shouldAutoScroll && activeIds.length > 0) {
        const firstActiveButton = buttonRefs.current[activeIds[0]];
        if (firstActiveButton && scrollContainerRef2.current) {
          scrollContainerRef2.current.scrollTo({
            left:
              firstActiveButton.offsetLeft -
              scrollContainerRef2.current.offsetWidth / 2 +
              firstActiveButton.offsetWidth / 2,
            behavior: "auto",
          });
        }
      }
    };

    // Attach to container or window
    const container = scrollContainerRef.current;
    if (container) {
      container.addEventListener("scroll", handlePageScroll);
      handlePageScroll({ target: container });
    } else {
      window.addEventListener("scroll", handlePageScroll);
      handlePageScroll();
    }

    return () => {
      if (container) {
        container.removeEventListener("scroll", handlePageScroll);
      } else {
        window.removeEventListener("scroll", handlePageScroll);
      }
    };
  }, [sections, shouldAutoScroll, scrollContainerRef]);

  return (
    <div
      className={cn(
        "sticky z-50 px-4 transition-all duration-200",
        isStuck ? "top-1 sm:top-2 md:top-4 rounded-lg" : "rounded-t-none"
      )}
    >
      <Card
        className={cn(
          "w-full bg-background transition-all duration-200",
          isStuck
            ? "rounded-lg mt-2 shadow-md"
            : "shadow-sm rounded-t-none border-t-0 -mt-6 pb-2"
        )}
      >
        <CardContent className="py-2 px-4">
          <div className="grid grid-cols-[1fr_auto] items-center min-w-0 relative">
            <div
              ref={scrollContainerRef2}
              className="overflow-x-auto no-scrollbar min-w-0 -mx-1 px-1 touch-pan-x overscroll-y-contain pr-12"
            >
              <div className="flex flex-nowrap space-x-1">
                {sections.map(({ id, label, responsiveIds }) => (
                  <Button
                    key={id}
                    ref={(el) => (buttonRefs.current[id] = el)}
                    variant={activeSections.includes(id) ? "default" : "ghost"}
                    size="sm"
                    className={cn(
                      "whitespace-nowrap flex-shrink-0 px-1 md:px-3 py-2 transition-all duration-200",
                      activeSections.includes(id) &&
                        "bg-blue-100 dark:bg-blue-900/70 text-primary dark:text-blue-100 shadow-sm hover:bg-blue-100 dark:hover:bg-blue-900/70 md:hover:bg-blue-200 dark:md:hover:bg-blue-900",
                      !activeSections.includes(id) &&
                        "hover:bg-blue-100 dark:hover:bg-blue-900/40 md:hover:bg-blue-50 dark:md:hover:bg-blue-900/20 hover:text-primary dark:hover:text-blue-100 dark:text-gray-400",
                      "focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-ring focus-visible:ring-offset-background",
                      "disabled:pointer-events-none disabled:opacity-50"
                    )}
                    onClick={() => handleSectionClick(id, responsiveIds)}
                  >
                    {label}
                  </Button>
                ))}
              </div>
            </div>
            <div className="absolute -right-2.5 top-0 bottom-0 flex items-center bg-background pl-1 pr-0">
              <Button
                variant="icon"
                size="sm"
                className={cn(
                  "flex-shrink-0 h-10 w-10 p-0 hover:bg-blue-100 dark:hover:bg-blue-900/40",
                  isStuck ? "" : "hidden"
                )}
                onClick={scrollToTop}
              >
                <ArrowUpToLine className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
};

export default Navigation;
