import React, {
  useEffect,
  useState,
  useRef,
  useContext,
  useCallback,
} from "react";
import { RightCircleOutlined, LeftCircleOutlined } from "@ant-design/icons";
import * as CategoryAPI from "../../../pages/api/category";
import styles from "./category.module.scss";
import { useRouter } from "next/router";
import { createBreadcrumb, getFlattenCategory } from "../../globalUtils/utils";
import shopConetxt from "../../../context/shopConetxt";

const CategoryNew: React.FC = () => {
  const { categoryTreeNested, setCategoryBreadcrumb } = useContext(shopConetxt);
  const [category, setCategory] = useState<any[]>([]);
  const [canScrollLeft, setCanScrollLeft] = useState(false);
  const [canScrollRight, setCanScrollRight] = useState(false);
  const router = useRouter();

  const scrollRef = useRef<HTMLDivElement>(null);
  const scrollAmount = 250;

  const extractCategories = useCallback((payload: any): any[] => {
    if (!payload) {
      return [];
    }

    if (Array.isArray(payload)) {
      return payload;
    }

    if (Array.isArray(payload?.data)) {
      return payload.data;
    }

    if (Array.isArray(payload?.data?.data)) {
      return payload.data.data;
    }

    if (Array.isArray(payload?.categories)) {
      return payload.categories;
    }

    if (Array.isArray(payload?.results)) {
      return payload.results;
    }

    return [];
  }, []);

  useEffect(() => {
    let isMounted = true;

    CategoryAPI.fetchHomeCategory()
      .then((res) => {
        if (!isMounted) {
          return;
        }
        const list = extractCategories(res);
        setCategory(list.filter(Boolean));
      })
      .catch(() => {
        if (!isMounted) {
          return;
        }
        setCategory([]);
      });

    return () => {
      isMounted = false;
    };
  }, [extractCategories, router.pathname]);

  const updateScrollState = useCallback(() => {
    const node = scrollRef.current;
    if (!node) {
      return;
    }
    const { scrollLeft, scrollWidth, clientWidth } = node;
    setCanScrollLeft(scrollLeft > 4);
    setCanScrollRight(scrollLeft + clientWidth < scrollWidth - 4);
  }, []);

  useEffect(() => {
    updateScrollState();
  }, [category.length, updateScrollState]);

  useEffect(() => {
    const node = scrollRef.current;
    if (!node) {
      return;
    }

    const handleResize = () => updateScrollState();

    node.addEventListener("scroll", updateScrollState, { passive: true });
    if (typeof window !== "undefined") {
      window.addEventListener("resize", handleResize);
    }

    return () => {
      node.removeEventListener("scroll", updateScrollState);
      if (typeof window !== "undefined") {
        window.removeEventListener("resize", handleResize);
      }
    };
  }, [updateScrollState]);

  const scheduleScrollUpdate = () => {
    if (typeof window !== "undefined") {
      window.setTimeout(updateScrollState, 250);
    }
  };

  const scrollLeft = () => {
    if (scrollRef.current) {
      scrollRef.current.scrollBy({ left: -scrollAmount, behavior: "smooth" });
      scheduleScrollUpdate();
    }
  };
  const scrollRight = () => {
    if (scrollRef.current) {
      scrollRef.current.scrollBy({ left: scrollAmount, behavior: "smooth" });
      scheduleScrollUpdate();
    }
  };

  const navigateToCategory = (data: any) => {
    const flattenCategory = getFlattenCategory(categoryTreeNested);
    const breadCrumbData = createBreadcrumb(data?.id, flattenCategory);

localStorage.setItem("WithoutProduct",data?.name)
    setCategoryBreadcrumb(breadCrumbData);
    router.push({
      pathname: `/products/${data.id}`,
    });
  };

  return (
    <div className={styles.categoryNewBar}>
      <button
        type="button"
        onClick={scrollLeft}
        className={styles.categoryNewArrow}
        aria-label="Scroll categories left"
        disabled={!canScrollLeft}
      >
        <LeftCircleOutlined className={styles.categoryNewArrowIcon} />
      </button>

      <div ref={scrollRef} className={styles.categoryNewScroll}>
        {category.map((cat: any) => (
          <button
            key={cat?.id ?? cat?.name}
            type="button"
            onClick={() => navigateToCategory(cat)}
            className={styles.categoryNewText}
          >
            {cat?.name}
          </button>
        ))}
      </div>

      <button
        type="button"
        onClick={scrollRight}
        className={styles.categoryNewArrow}
        aria-label="Scroll categories right"
        disabled={!canScrollRight}
      >
        <RightCircleOutlined className={styles.categoryNewArrowIcon} />
      </button>
    </div>
  );
};

export default CategoryNew;
