"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,
  getAllCategories,
  getAllSubCategory,
} from "../../features/master/masterSlice";
import {
  getAllProducts,
  getGroupByProduct,
} 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 { useSearchParams } from "next/navigation";

const STEP = 4;

function SubCategories() {
  const searchParams = useSearchParams();

  const categoryId = searchParams.get("category_id") || "";
  const subcategoryId = searchParams.get("sub_category_id") || "";
  const categoryImage = searchParams.get("category_image") || "";

  const [selectedCategoryId, setSelectedCategoryId] = useState(categoryId);
  const [selectedSubCategory, setSelectedSubCategory] = useState(subcategoryId);
  useEffect(() => {
    setSelectedCategoryId(categoryId);
    setSelectedSubCategory(subcategoryId);
  }, [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(getGroupByProduct());

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

  useEffect(() => {
    dispatch(getGroupByProduct({ p_category_id: categoryId }));
  }, [dispatch, categoryId]);

  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 [childList, setChildList] = useState([]);
  const [childStatus, setChildStatus] = useState(""); // noChild

  useEffect(() => {
    dispatch(getAllSubCategory({ category_id: categoryId }));
  }, [categoryId]);

  useEffect(() => {
    dispatch(
      getAllProducts({
        category_id: categoryId,
        subcategory_id: selectedSubCategory,
      }),
    );
  }, [categoryId, selectedSubCategory]);

  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: 10 },
                    992: { slidesPerView: 6, spaceBetween: 10 },
                    1200: { slidesPerView: 6, spaceBetween: 10 },
                  }}
                >
                  <SwiperSlide key="" className="product-slide">
                    <Nav.Item>
                      <Nav.Link
                        eventKey=""
                        className={
                          selectedSubCategory === "" ? "activecategory" : ""
                        }
                        onClick={() => {
                          setSelectedSubCategory("");
                        }}
                      >
                        <Category_Subcategory_Card
                          className="product-image"
                          content="All Product"
                          image={
                            process.env.NEXT_PUBLIC_IMG_URL + categoryImage ||
                            appSetupdata?.qr_image
                          }
                          imgClassName="category-image"
                        />
                        <div className="triangle-right"></div>
                      </Nav.Link>
                    </Nav.Item>
                  </SwiperSlide>
                  {subcategories?.map((slide, index) => (
                    <SwiperSlide key={index} className="product-slide">
                      <Nav.Item>
                        <Nav.Link
                          eventKey={slide?.id}
                          className={
                            Number(selectedSubCategory) === Number(slide?.id)
                              ? "activecategory"
                              : ""
                          }
                          // className={
                          //   category_Id
                          //     ? String(category_Id) === String(slide?.id)
                          //       ? "activecategory"
                          //       : ""
                          //     : Number(selectedCategoryId) === Number(slide?.id)
                          //     ? "activecategory"
                          //     : ""
                          // }
                          onClick={() => {
                            setSelectedSubCategory(slide?.id);

                            // Clear category_Id by resetting state
                            // navigate(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"
                      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 SubCategories;
