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

const Navigation = () => {
  const [activeSections, setActiveSections] = useState([]);
  const { isStuck } = useScroll();
  const buttonRefs = useRef({});
  const scrollContainerRef = useRef(null);
  const [shouldAutoScroll, setShouldAutoScroll] = useState(true);
  const lastScrollLeft = useRef(0);
  const lastScrollTop = useRef(
    window.pageYOffset || document.documentElement.scrollTop
  );

  // Define base sections that are always visible
  const baseSections = [
    { id: "stats", label: "Statistics" },
    {
      id: "realtime",
      label: "Realtime",
      responsiveIds: ["realtime-lg", "realtime-md"],
      order: { md: 2, default: 1 },
    },
    {
      id: "products",
      label: "Top Products",
      responsiveIds: ["products-lg", "products-md"],
      order: { md: 1, default: 2 },
    },
    { id: "feed", label: "Activity Feed" },
    { id: "sales", label: "Sales Metrics" },
    { id: "campaigns", label: "Campaigns" },
    { id: "meta", label: "Meta Ads" },
    { id: "analytics", label: "Analytics" },
    { id: "behavior", label: "User Behavior" },
    { id: "gorgias", label: "Customer Service" },
    { id: "calls", label: "Calls" },
  ];

  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 = () => {
    window.scrollTo({
      top: 0,
      behavior: "smooth",
    });
  };

  const scrollToSection = (sectionId, responsiveIds) => {
    if (responsiveIds) {
      const visibleId = responsiveIds.find((id) => {
        const element = document.getElementById(id);
        if (!element) return false;
        const style = window.getComputedStyle(element);
        return style.display !== "none";
      });

      if (visibleId) {
        sectionId = visibleId;
      }
    }

    const element = document.getElementById(sectionId);
    if (element) {
      const offset = element.offsetTop - 80;
      window.scrollTo({
        top: offset,
        behavior: "smooth",
      });
    }
  };

  // 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 = () => {
      const 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;

      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;

            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) {
            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 && scrollContainerRef.current) {
          scrollContainerRef.current.scrollTo({
            left:
              firstActiveButton.offsetLeft -
              scrollContainerRef.current.offsetWidth / 2 +
              firstActiveButton.offsetWidth / 2,
            behavior: "auto",
          });
        }
      }
    };

    window.addEventListener("scroll", handlePageScroll);
    handlePageScroll();
    return () => window.removeEventListener("scroll", handlePageScroll);
  }, [sections, shouldAutoScroll]);

  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-white dark:bg-gray-900 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={scrollContainerRef}
              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={() => scrollToSection(id, responsiveIds)}
                  >
                    {label}
                  </Button>
                ))}
              </div>
            </div>
            <div className="absolute -right-2.5 top-0 bottom-0 flex items-center bg-white dark:bg-gray-900 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;
