import React, { useRef } from "react";
import { useNavigate } from "react-router-dom";
import { useGetCategoriesQuery } from "../../app/api/categories.js";
import styles from "./CategoryCarousel.module.scss";

const CategoryCarousel = () => {
  const { data, isLoading } = useGetCategoriesQuery("tree");
  const scrollRef = useRef(null);
  const navigate = useNavigate();

  const isDragging = useRef(false);
  const startX = useRef(0);
  const scrollLeft = useRef(0);
  const hasDragged = useRef(false);

  const mainCategories =
    data?.data?.filter((cat) => cat.parent_id === null) ?? [];

  const scroll = (dir) => {
    if (!scrollRef.current) return;
    scrollRef.current.scrollBy({ left: dir * 320, behavior: "smooth" });
  };

  const onMouseDown = (e) => {
    isDragging.current = true;
    hasDragged.current = false;
    startX.current = e.pageX - scrollRef.current.offsetLeft;
    scrollLeft.current = scrollRef.current.scrollLeft;
    scrollRef.current.style.cursor = "grabbing";
  };

  const onMouseMove = (e) => {
    if (!isDragging.current) return;
    e.preventDefault();
    const x = e.pageX - scrollRef.current.offsetLeft;
    const walk = x - startX.current;
    if (Math.abs(walk) > 4) hasDragged.current = true;
    scrollRef.current.scrollLeft = scrollLeft.current - walk;
  };

  const onMouseUp = () => {
    isDragging.current = false;
    if (scrollRef.current) scrollRef.current.style.cursor = "grab";
  };

  const handleCardClick = (e, slug) => {
    if (hasDragged.current) {
      e.preventDefault();
      return;
    }
    navigate(`/category/${slug}`);
  };

  if (isLoading || mainCategories.length === 0) return null;

  return (
    <div className={styles.wrapper}>
      <button
        className={`${styles.arrow} ${styles.left}`}
        onClick={() => scroll(-1)}
        aria-label="Scroll left"
      >
        ‹
      </button>

      <div
        className={styles.track}
        ref={scrollRef}
        onMouseDown={onMouseDown}
        onMouseMove={onMouseMove}
        onMouseUp={onMouseUp}
        onMouseLeave={onMouseUp}
      >
        {mainCategories.map((cat) => {
          const thumb =
            cat.media?.[0]?.images_400x400 ??
            cat.media?.[0]?.thumbnail ??
            null;

          return (
            <div
              key={cat.id}
              className={styles.card}
              onClick={(e) => handleCardClick(e, cat.slug)}
            >
              <div className={styles.imgWrap}>
                {thumb ? (
                  <img
                    src={thumb}
                    alt={cat.name}
                    loading="lazy"
                    draggable={false}
                  />
                ) : (
                  <div className={styles.placeholder} />
                )}
              </div>
              <span className={styles.name}>{cat.name}</span>
            </div>
          );
        })}
      </div>

      <button
        className={`${styles.arrow} ${styles.right}`}
        onClick={() => scroll(1)}
        aria-label="Scroll right"
      >
        ›
      </button>
    </div>
  );
};

export default CategoryCarousel;