"use client";

import React, { useEffect, useLayoutEffect, 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 {
  appSetup,
  getAllSubCategory,
  getAllChildCategory,
  AllBrands,
} 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";

import CategorySidebar from "./category_sidebar/CategorySidebar";
import Offcanvas from "react-bootstrap/Offcanvas";
import Button from "react-bootstrap/Button";
import { FaFilter } from "react-icons/fa";
const STEP = 4;

import { FaPlus, FaMinus } from "react-icons/fa";
import SupermarketCart from "../Animation/supermarket-cart/SupermarketCart";
import Pagination_Holder from "../common-components/pagination_holder/Pagination_Holder";
function Categories() {
  const [openCategory, setOpenCategory] = useState("main");
  const [expandedCategory, setExpandedCategory] = useState(null);
  const [expandedSubCategory, setExpandedSubCategory] = useState(null);
  const [openBrand, setOpenBrand] = useState(false);
  const navigate = useRouter();
  const searchParams = useSearchParams();
  const categoryId = searchParams.get("category_id") || "";
  const subcategoryId = searchParams.get("subcategory_id");
  const childCategoryId = searchParams.get("childcategory_id");
  const brandId = searchParams.get("brand_id") || "";
  const fromHeader = searchParams.get("fromHeader");

  const [onPageChange, setOnPageChange] = useState(1);
  const [totalPages, setTotalPages] = useState(1);

  const handlePageChange = (pageNumber) => {
    setOnPageChange(pageNumber);
  };
  /*-------- new for reset---------*/
  useEffect(() => {
    const handleBeforeUnload = () => {
      sessionStorage.setItem("SHOP_REFRESH", "true");
    };
    window.addEventListener("beforeunload", handleBeforeUnload);
    return () => {
      window.removeEventListener("beforeunload", handleBeforeUnload);
    };
  }, []);
  useEffect(() => {
    if (sessionStorage.getItem("SHOP_REFRESH") === "true") {
      sessionStorage.removeItem("SHOP_REFRESH");
      navigate.replace("/shop");
    }
  }, [navigate]);
  /*------------------------------ */
  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([]);

  const handleToggle = (index, totalProducts, categoryId) => {
    setVisibleCounts((prevCounts) => {
      const newCounts = prevCounts.map((count, i) =>
        i === index
          ? count >= totalProducts
            ? STEP
            : Math.min(count + STEP, totalProducts)
          : count,
      );

      if (prevCounts[index] >= totalProducts) {
        const el = document.getElementById(categoryId);
        if (el) {
          setTimeout(() => {
            el.scrollIntoView({ behavior: "smooth", block: "start" });
          }, 100);
        }
      }

      return newCounts;
    });
  };

  const category_Id = location.state?.category_id;

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

  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 childCategories = useSelector((state) => state.master.childcategories);
  const allbrands = useSelector((state) => state?.master?.brands);
  const appSetupdata = useSelector((state) => state.master.app_setup);

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

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

    const selected = subcategories.find((s) => s.id === subId);

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

    const res = await dispatch(
      getAllChildCategory({
        subcategory_id: subId,
      }),
    );
  };

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

  useEffect(() => {
    dispatch(
      getAllProducts({
        category_id: categoryId || "",
        subcategory_id: subcategoryId || "",
        childcategory_id: childCategoryId || "",
        brand_id: brandId || "",
        name: search || "",
        page: onPageChange,
      }),
    );
  }, [
    categoryId,
    subcategoryId,
    childCategoryId,
    brandId,
    search,
    onPageChange,
  ]);
  useEffect(() => {
    if (all_products && all_products.data) {
      setTotalPages(all_products.total_pages);
      setOnPageChange(all_products.current_page);
    }
  }, [all_products]);

  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("");

  useEffect(() => {
    dispatch(appSetup());
    dispatch(AllBrands());
  }, [dispatch]);

  const [showFilter, setShowFilter] = useState(false);

  const handleClose = () => setShowFilter(false);
  const handleShow = () => setShowFilter(true);

  /*------------------------------ */

  useEffect(() => {
    if (!categoryId) {
      setSelectedCategoryId("");
      setExpandedCategory(null);
      setExpandedSubCategory(null);
      setSelectedSubCategory("");
      setChildList([]);
      return;
    }

    setSelectedCategoryId(categoryId);
    setExpandedCategory(Number(categoryId));

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

  useEffect(() => {
    if (!subcategoryId) {
      setExpandedSubCategory(null);
      return;
    }

    setExpandedSubCategory(Number(subcategoryId));

    dispatch(
      getAllChildCategory({
        subcategory_id: subcategoryId,
      }),
    );
  }, [subcategoryId, dispatch]);
  useEffect(() => {
    window.scrollTo({
      top: 0,
      behavior: "smooth",
    });
  }, [categoryId, subcategoryId, childCategoryId, brandId]);

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

      <div className="container">
        <Row>
          <div className="d-lg-none mb-3">
            <Button className="filter_btn" onClick={handleShow}>
              <FaFilter /> Filters
            </Button>
          </div>
          <Col md={4} lg={3} xl={3} className="d-none d-lg-block">
            <CategorySidebar
              category={category}
              subcategories={subcategories}
              childCategories={childCategories}
              brands={allbrands}
              brandId={brandId}
              openCategory={openCategory}
              setOpenCategory={setOpenCategory}
              expandedCategory={expandedCategory}
              setExpandedCategory={setExpandedCategory}
              expandedSubCategory={expandedSubCategory}
              setExpandedSubCategory={setExpandedSubCategory}
              selectedCategoryId={selectedCategoryId}
              setSelectedCategoryId={setSelectedCategoryId}
              dispatch={dispatch}
              getAllSubCategory={getAllSubCategory}
              handleSubCategoryClick={handleSubCategoryClick}
              openBrand={openBrand}
              setOpenBrand={setOpenBrand}
              categoryId={categoryId}
              subcategoryId={subcategoryId}
              childCategoryId={childCategoryId}
            />
          </Col>
          <Col xl={9} lg={9}>
            <div className="Categories">
              <>
                <div className="row px-2">
                  {all_products?.data?.length > 0 ? (
                    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-xl-3 col-lg-3   col-md-3 col-sm-4 col-6 px-md-2 custom_5_co mb-1 px-1"
                          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}
                            variant={activeVariant || ""}
                            kgText={activeVariant?.name}
                            savingPrice={
                              parseFloat(activeVariant?.mrp || 0) -
                              parseFloat(activeVariant?.price || 0)
                            }
                            showQty
                          />
                        </div>
                      );
                    })
                  ) : (
                    <div className="col-12 text-center">
                      <div className="lottie_div">
                        <SupermarketCart />
                      </div>
                      <h5 className="no-found">No products found</h5>
                      <p className="no-found-sub">
                        Please try another category or filter.
                      </p>
                    </div>
                  )}
                </div>
              </>
            </div>{" "}
            <div className="pagination_div">
              <Pagination_Holder
                onPageChange={onPageChange}
                totalPages={totalPages}
                handlePageChange={handlePageChange}
              />
            </div>
          </Col>
        </Row>
      </div>
      <Offcanvas show={showFilter} onHide={handleClose} placement="start">
        <Offcanvas.Header closeButton>
          <Offcanvas.Title>Filters</Offcanvas.Title>
        </Offcanvas.Header>

        <Offcanvas.Body>
          <CategorySidebar
            category={category}
            subcategories={subcategories}
            childCategories={childCategories}
            brands={allbrands}
            brandId={brandId}
            openCategory={openCategory}
            setOpenCategory={setOpenCategory}
            expandedCategory={expandedCategory}
            setExpandedCategory={setExpandedCategory}
            expandedSubCategory={expandedSubCategory}
            setExpandedSubCategory={setExpandedSubCategory}
            selectedCategoryId={selectedCategoryId}
            setSelectedCategoryId={setSelectedCategoryId}
            dispatch={dispatch}
            getAllSubCategory={getAllSubCategory}
            handleSubCategoryClick={handleSubCategoryClick}
            openBrand={openBrand}
            setOpenBrand={setOpenBrand}
            categoryId={categoryId}
            subcategoryId={subcategoryId}
            childCategoryId={childCategoryId}
          />
        </Offcanvas.Body>
      </Offcanvas>
    </section>
  );
}

export default Categories;
