import { Card, Grid, Space } from "antd";
import ImageWithFallback from "components/ImageWithFallback";
import ProText from "components/ProText";
import { useScrollHandler } from "contexts/ScrollHandlerContext";
import { useCallback, useEffect, useRef } from "react";
import { useAppSelector } from "redux/hooks";
import { colors } from "ThemeConstants";
import { default_image } from "utils/constants";
import { Category } from "utils/types/appTypes";
import styles from "./CategoriesList.module.css";

interface CategoriesListProps {
  categories: Category[];
}

const { useBreakpoint } = Grid;

export function CategoriesList({ categories }: CategoriesListProps) {
  const { xs, md } = useBreakpoint();
  const {
    isCategoriesSticky,
    categoriesContainerRef,
    scrollToCategory,
    activeCategory,
    setActiveCategory,
  } = useScrollHandler();
  const { isRTL } = useAppSelector((state) => state.locale);

  // Drag scroll functionality (desktop only)
  const isDragging = useRef(false);
  const startX = useRef(0);
  const scrollLeft = useRef(0);

  // Only enable drag on desktop (not mobile or tablet)
  const isDesktop = !xs;

  const getCategoryCardStyle = useCallback(() => {
    if (xs) {
      return {
        width: 90,
        height: isCategoriesSticky ? 38 : 110,
      };
    } else if (md) {
      return {
        width: 120,
        height: isCategoriesSticky ? 38 : 110,
      };
    } else {
      return {
        width: 140,
        height: isCategoriesSticky ? 38 : 160,
      };
    }
  }, [isCategoriesSticky, xs, md]);

  // Set first category as active on initial load
  useEffect(() => {
    if (categories.length > 0 && !activeCategory) {
      setActiveCategory(categories[0].id);
    }
  }, [categories, activeCategory, setActiveCategory]);

  // Function to scroll category card into view when active category changes automatically
  const scrollCategoryCardIntoView = useCallback((categoryId: number) => {
    const categoryCard = document.querySelector(
      `[data-category-id="${categoryId}"]`,
    );
    if (categoryCard) {
      const categoriesContainer = categoryCard.closest(
        `.${styles.categoriesContainer}`,
      );
      if (categoriesContainer) {
        const cardElement = categoryCard as HTMLElement;
        const containerElement = categoriesContainer as HTMLElement;
        const cardRect = cardElement.getBoundingClientRect();
        const containerRect = containerElement.getBoundingClientRect();

        if (
          cardRect.left < containerRect.left ||
          cardRect.right > containerRect.right
        ) {
          cardElement.scrollIntoView({
            behavior: "smooth",
            block: "nearest",
            inline: "center",
          });
        }
      }
    }
  }, []);

  // Auto-scroll category card into view when active category changes
  useEffect(() => {
    if (activeCategory) {
      // Use a small delay to ensure the DOM has updated
      const timer = setTimeout(() => {
        scrollCategoryCardIntoView(activeCategory);
      }, 150);

      return () => clearTimeout(timer);
    }
  }, [activeCategory, scrollCategoryCardIntoView]);

  // Drag scroll event handlers (desktop only)
  const handleMouseDown = useCallback(
    (e: React.MouseEvent) => {
      if (!isDesktop) return;

      const container = categoriesContainerRef?.current;
      if (!container) return;

      isDragging.current = true;
      startX.current = e.pageX - container.offsetLeft;
      scrollLeft.current = container.scrollLeft;

      // Prevent text selection during drag
      e.preventDefault();
    },
    [categoriesContainerRef, isDesktop],
  );

  const handleMouseMove = useCallback(
    (e: React.MouseEvent) => {
      // Only enable drag on desktop
      if (!isDesktop) return;

      const container = categoriesContainerRef?.current;
      if (!container || !isDragging.current) return;

      e.preventDefault();
      const x = e.pageX - container.offsetLeft;
      const walk = (x - startX.current) * 2; // Multiply for faster scrolling
      container.scrollLeft = scrollLeft.current - walk;
    },
    [categoriesContainerRef, isDesktop],
  );

  const handleMouseUp = useCallback(() => {
    isDragging.current = false;
  }, []);

  const handleMouseLeave = useCallback(() => {
    isDragging.current = false;
  }, []);

  // Touch event handlers - disabled for mobile/tablet (use native scroll)
  const handleTouchStart = useCallback(() => {
    // Disable custom touch handling - let native scroll work
    return;
  }, []);

  const handleTouchMove = useCallback(() => {
    // Disable custom touch handling - let native scroll work
    return;
  }, []);

  const handleTouchEnd = useCallback(() => {
    // Disable custom touch handling - let native scroll work
    return;
  }, []);

  return (
    <>
      <div
        ref={categoriesContainerRef as React.RefObject<HTMLDivElement>}
        className={`${styles.categoriesContainer} ${
          isCategoriesSticky ? styles.categoriesSticky : ""
        }`}
        style={!isCategoriesSticky ? { paddingTop: "1rem" } : {}}
        onMouseDown={handleMouseDown}
        onMouseMove={handleMouseMove}
        onMouseUp={handleMouseUp}
        onMouseLeave={handleMouseLeave}
        onTouchStart={handleTouchStart}
        onTouchMove={handleTouchMove}
        onTouchEnd={handleTouchEnd}
      >
        {categories?.map((category) => (
          <div key={category.id}>
            <Card
              key={category.id}
              onClick={(e) => {
                // Prevent click if we were dragging
                if (isDragging.current) {
                  e.preventDefault();
                  return;
                }
                scrollToCategory(category.id);
              }}
              data-category-id={category.id}
              style={{
                borderRadius: 8,
                border: "none",
              }}
              styles={{
                body: {
                  ...getCategoryCardStyle(),
                  width: 105,
                  padding: 0,
                },
              }}
              className={`${
                activeCategory === category.id ? styles.activeCategoryCard : ""
              }`}
            >
              <div
                style={{
                  display: "flex",
                  flexDirection: "column",
                  alignItems: "center",
                  justifyContent: "space-between",
                  gap: "0px",
                  width: "100%",
                  height: "100%",
                  overflow: "hidden",
                }}
              >
                {!isCategoriesSticky && (
                  <ImageWithFallback
                    src={category.image || default_image}
                    fallbackSrc={default_image}
                    alt={category.name}
                    className={`${styles.categoryMenuItemImage} ${
                      xs
                        ? styles.categoryMenuItemImageMobile
                        : md
                          ? styles.categoryMenuItemImageTablet
                          : styles.categoryMenuItemImageDesktop
                    }`}
                    // {...getCategoryImageStyle()}
                    width={105}
                    height={80}
                    style={{
                      borderEndEndRadius: isCategoriesSticky ? 8 : 0,
                      borderEndStartRadius: isCategoriesSticky ? 8 : 0,
                    }}
                    loadingContainerStyle={{
                      borderEndEndRadius: isCategoriesSticky ? 8 : 0,
                      borderEndStartRadius: isCategoriesSticky ? 8 : 0,
                    }}
                  />
                )}

                <Space
                  direction="vertical"
                  size="small"
                  style={{
                    flex: 1,
                    padding: xs ? "4px" : md ? "4px" : "4px",
                    textAlign: "center",
                    ...(xs || md
                      ? {
                          // backgroundColor: "#fff6e0",
                          borderBottom: "solid 1px var(--primary)",
                          borderRight: "solid 1px var(--primary)",
                          borderLeft: "solid 1px var(--primary)",
                          borderTop: isCategoriesSticky
                            ? "solid 1px var(--primary)"
                            : 0,
                          borderStartStartRadius: isCategoriesSticky ? 8 : 0,
                          borderStartEndRadius: isCategoriesSticky ? 8 : 0,
                          borderEndEndRadius: 8,
                          borderEndStartRadius: 8,
                          backgroundColor:
                            activeCategory === category.id
                              ? colors.primary
                              : undefined,
                        }
                      : { borderRadius: 8 }),
                    width: 104,
                    height: 30,
                    marginBottom: 1,
                  }}
                >
                  <ProText
                    style={{
                      margin: 0,
                      lineClamp: 1,
                      WebkitBoxOrient: "vertical",
                      WebkitLineClamp: 1,
                      lineHeight: isCategoriesSticky ? "1.5" : "1",
                      maxHeight: "2.8em",
                      textAlign: "center",

                      color:
                        activeCategory === category.id ? "#FFF" : undefined,
                      fontWeight:
                        activeCategory === category.id ? "600" : "500",
                      whiteSpace: "nowrap",
                      overflow: "hidden",
                      textOverflow: "ellipsis",
                      padding: 3,
                      fontSize: xs ? 14 : md ? 14 : 16,
                      width: xs ? 80 : md ? 100 : 120,
                      display: "inline-block",
                    }}
                  >
                    {isRTL
                      ? category.name || category.nameEN
                      : category.nameEN || category.name}
                  </ProText>
                </Space>
              </div>
            </Card>
          </div>
        ))}
      </div>
    </>
  );
}
