"use client";

import React, { useEffect, useState } from "react";
import "./Categories.css";
import Breadcrumb_comp from "../common-components/breadcrumb-comp/Breadcrumb_comp";
import { useDispatch, useSelector } from "react-redux";
import { appSetup } from "../../features/master/masterSlice";
import { getAllProducts } from "../../features/products/productsSlice";
import Product_Info_Card from "../common-components/product_info_card/Product_Info_Card";
import { Swiper, SwiperSlide } from "swiper/react";
import { Navigation, Pagination } from "swiper/modules";
import "swiper/css";
import "swiper/css/pagination";
import "swiper/css/navigation";
import { Container, Row, Col, Tab, Nav } from "react-bootstrap";
import Category_Subcategory_Card from "../common-components/category_subcategory_card/Category_Subcategory_Card";
import { variant_type } from "../../utils/common";
import { useRouter, useSearchParams } from "next/navigation";
const STEP = 4;

function Categories() {
  const navigate = useRouter();
  const searchParams = useSearchParams();
  const categoryId = searchParams.get("category_id") || "";
  const [selectedCategoryId, setSelectedCategoryId] = useState(categoryId);
  useEffect(() => {
    setSelectedCategoryId(categoryId);
  }, [categoryId]);
  const dispatch = useDispatch();

  const [swiperInstance, setSwiperInstance] = useState(null);

  const categoryWiseProduct = useSelector(
    (state) => state.product.allProductsGroup,
  );

  const breadcrumbs = [
    { label: "Home", link: "/", isActive: false },
    { label: "Categories", link: "", isActive: true },
  ];

  const [visibleCounts, setVisibleCounts] = useState([]);

  // Scroll to a specific category section when "See Less" is clicked
  const handleToggle = (index, totalProducts, categoryId) => {
    setVisibleCounts((prevCounts) => {
      const newCounts = prevCounts.map((count, i) =>
        i === index
          ? count >= totalProducts
            ? STEP
            : Math.min(count + STEP, totalProducts)
          : count,
      );

      // Scroll if reducing to STEP
      if (prevCounts[index] >= totalProducts) {
        const el = document.getElementById(categoryId);
        if (el) {
          setTimeout(() => {
            el.scrollIntoView({ behavior: "smooth", block: "start" });
          }, 100); // delay to ensure layout update
        }
      }

      return newCounts;
    });
  };

  // const location = useLocation();

  const category_Id = location.state?.category_id;

  useEffect(() => {
    dispatch(getAllProducts());

    if (location.hash) {
      const id = location.hash.replace("#", "");
      const el = document.getElementById(id);
      if (el) {
        el.scrollIntoView({ behavior: "smooth" });
      }
    }
  }, [location, dispatch]);

  useEffect(() => {
    if (categoryWiseProduct?.data) {
      setVisibleCounts(new Array(categoryWiseProduct.data.length).fill(STEP));
    }
  }, [categoryWiseProduct]);

  useEffect(() => {
    const scrollToId = location.state?.scrollToId;
    if (scrollToId) {
      const scroll = () => {
        const element = document.getElementById(scrollToId);
        if (element) {
          element.scrollIntoView({ behavior: "smooth", block: "start" });
        } else {
          setTimeout(scroll, 100);
        }
      };
      scroll();
    }
  }, [location.state]);

  const category = useSelector((state) => state.master.categories);
  const subcategories = useSelector((state) => state.master.subcategories);
  const all_products = useSelector((state) => state.product.allProducts);

  const [selectedSubCategory, setSelectedSubCategory] = useState("");
  const [childList, setChildList] = useState([]);
  const [childStatus, setChildStatus] = useState(""); // noChild

  // const handleCategoryClick = (category_id) => {
  //   setStatus("");
  //   // dispatch(getAllSubCategory({ category_id }));
  // };

  const handleSubCategoryClick = (categoryId, subId) => {
    setSelectedCategoryId(categoryId);
    setSelectedSubCategory(subId);

    // Find the clicked subcategory
    const selected = subcategories.find((s) => s.id === subId);

    // Populate child list
    if (!selected || !selected.children || selected.children.length === 0) {
      setChildList([]);
      setChildStatus("noChild");
    } else {
      setChildList(selected.children);
      setChildStatus("");
    }

    // Load products
    dispatch(
      getAllProducts({
        category_id: categoryId,

        // subcategory_id: subId,
      }),
    );
  };

  const search = searchParams.get("search");

  useEffect(() => {
    dispatch(
      getAllProducts({
        category_id: selectedCategoryId,
        name: search || "",
        // subcategory_id: subcategories?.[0]?.id,
      }),
    );
  }, [selectedCategoryId, search]);

  useEffect(() => {
    dispatch(
      getAllProducts({
        p_category_id: categoryId,
        name: search || "",
      }),
    );
  }, [dispatch, categoryId, search]);

  useEffect(() => {
    if (status === "noCategory" || status === "noSubcategory") return;

    if (!all_products?.data || all_products.data.length === 0) {
      setStatus("noProducts");
      return;
    }

    setStatus("");
  }, [all_products]);

  const [status, setStatus] = useState("");
  const appSetupdata = useSelector((state) => state.master.app_setup);
  useEffect(() => {
    dispatch(appSetup());
  }, [dispatch]);

  return (
    <section className="Categories_section_holder">
      <div className="container">
        <div className="Categories">
          <Breadcrumb_comp breadcrumbs={breadcrumbs} />

          {/* new code for subcategories */}

          {/* <div className="heading_holder">
            <h4 className="heading_text">Explore Collection</h4>
          </div>

          <div className="cat_subcat_div">
            {status === "noCategory" ? (
              <p className="text-danger">No category available.</p>
            ) : (
              <div variant="pills" className="flex-row p-0 mb-3">
                <Swiper
                  className="mySwiper "
                  onSwiper={(swiper) => setSwiperInstance(swiper)}
                  // pagination={{
                  //   dynamicBullets: true,
                  //   clickable: true,
                  // }}
                  modules={[Pagination, Navigation]}
                  breakpoints={{
                    0: { slidesPerView: 2, spaceBetween: 10 },
                    350: { slidesPerView: 3, spaceBetween: 10 },
                    486: { slidesPerView: 3, spaceBetween: 10 },
                    576: { slidesPerView: 4, spaceBetween: 10 },
                    768: { slidesPerView: 5, spaceBetween: 20 },
                    992: { slidesPerView: 6, spaceBetween: 20 },
                    1200: { slidesPerView: 6, spaceBetween: 20 },
                  }}
                >
                  <SwiperSlide key="" className="product-slide">
                    <Nav.Item>
                      <Nav.Link
                        eventKey=""
                        className={
                          selectedCategoryId === "" ? "activecategory" : ""
                        }
                        onClick={() => {
                          setSelectedCategoryId("");

                          // Clear category_Id by resetting state
                          navigate.push(location.pathname, {
                            replace: true,
                            state: {},
                          });

                          // handleCategoryClick(slide?.id);
                        }}
                      >
                        <Category_Subcategory_Card
                          className="product-image"
                          content="All Product"
                          image={
                            process.env.NEXT_PUBLIC_IMG_URL +
                            appSetupdata?.qr_image
                          }
                          imgClassName="category-image"
                        />
                        <div className="triangle-right"></div>
                      </Nav.Link>
                    </Nav.Item>
                  </SwiperSlide>
                  {category?.map((slide, index) => (
                    <SwiperSlide key={index} className="product-slide">
                      <Nav.Item>
                        <Nav.Link
                          eventKey={slide?.id}
                          className={
                            Number(selectedCategoryId) === Number(slide?.id)
                              ? "activecategory"
                              : ""
                          }
                          onClick={() => {
                            setSelectedCategoryId(slide?.id);

                            // Clear category_Id by resetting state
                            navigate.push(location.pathname, {
                              replace: true,
                              state: {},
                            });

                            // handleCategoryClick(slide?.id);
                          }}
                        >
                          <Category_Subcategory_Card
                            className="product-image"
                            content={slide?.name}
                            image={
                              process.env.NEXT_PUBLIC_IMG_URL + slide?.image
                            }
                            imgClassName="category-image"
                          />
                          <div className="triangle-right"></div>
                        </Nav.Link>
                      </Nav.Item>
                    </SwiperSlide>
                  ))}
                </Swiper>
              </div>
            )}
          </div> */}

          {status === "noCategory" ||
          status === "noSubcategory" ? null : status === "noProducts" ? (
            <p className="text-danger">
              No products available for this selection.
            </p>
          ) : (
            <>
              <div className="heading_holder">
                <h4 className="heading_text">Products</h4>
              </div>

              <div className="row">
                {all_products?.data?.map((product, index) => {
                  let metal;
                  let size;
                  let triple;
                  if (
                    Number(product?.variant_type_id) ===
                    Number(variant_type.Single)
                  ) {
                    metal = product?.Product_Variants?.[0];
                  } else if (
                    Number(product?.variant_type_id) ===
                    Number(variant_type.Double)
                  ) {
                    metal = product?.Product_Variants?.[0];
                    size = metal?.Double_Variants?.[0];
                  } else if (
                    Number(product?.variant_type_id) ===
                    Number(variant_type.Triple)
                  ) {
                    metal = product?.Product_Variants?.[0];
                    size = metal?.Double_Variants?.[0];
                    triple = size?.Triple_Variants?.[0];
                  }

                  const activeVariant = triple || size || metal;

                  return (
                    <div
                      className="col-lg-4 col-md-4 col-sm-6 col-6 px-md-2 px-1 custom_5_col mb-3"
                      key={product?.id || index}
                    >
                      <Product_Info_Card
                        product={product}
                        id={product?.id}
                        imgSrc={
                          process.env.NEXT_PUBLIC_IMG_URL + product?.image
                        }
                        vdoSrc={
                          process.env.NEXT_PUBLIC_IMG_URL + product?.video
                        }
                        productName={product?.name}
                        priceText={activeVariant?.price || 0}
                        mrp={activeVariant?.mrp || 0}
                        kgText={activeVariant?.name}
                        savingPrice={
                          parseFloat(activeVariant?.mrp || 0) -
                          parseFloat(activeVariant?.price || 0)
                        }
                        showQty
                      />
                    </div>
                  );
                })}
              </div>
            </>
          )}
        </div>
      </div>
    </section>
  );
}

export default Categories;
