"use client";

import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { Nav } from "react-bootstrap";
import { useDispatch, useSelector } from "react-redux";
import "swiper/css";
import "swiper/css/navigation";
import "swiper/css/pagination";
import { Navigation, Pagination } from "swiper/modules";
import { Swiper, SwiperSlide } from "swiper/react";
import NoData from "../Animation/no_data/NoData";
import { getAllProducts } from "../../features/products/productsSlice";
import { variant_type } from "../../utils/common";
import Breadcrumb_comp from "../common-components/breadcrumb-comp/Breadcrumb_comp";
import Category_Subcategory_Card from "../common-components/category_subcategory_card/Category_Subcategory_Card";
import Product_Info_Card from "../common-components/product_info_card/Product_Info_Card";
import "./Categories.css";
import { usePathname } from "next/navigation";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faFilter } from "@fortawesome/free-solid-svg-icons";
import { Autoplay } from "swiper/modules";
import Pagination_Holder from "../common-components/pagination_holder/Pagination_Holder";

import {
  appSetup,
  getAllCategories,
  getAllCOLOURS,
  getAllSIZES,
} from "../../features/master/masterSlice";
import Filter_offcanvas from "../common-components/filter_offcanvas/Filter_offcanvas";
const STEP = 4;

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

  const searchParams = useSearchParams();
  const categoryId = searchParams.get("category_id") || "";

  const [selectedCategories, setSelectedCategories] = useState(
    categoryId ? [Number(categoryId)] : [],
  );
  const [showFilter, setShowFilter] = useState(false);
  // const [price, setPrice] = useState(10000);
  const [selectedSizes, setSelectedSizes] = useState([]);
  const [selectedColours, setSelectedColours] = useState([]);
  const [onPageChange, setOnPageChange] = useState(1);
  const [totalPages, setTotalPages] = useState(1);

  const [price, setPrice] = useState(null); // selected max
  const [minPrice, setMinPrice] = useState(null);

  const [tempCategories, setTempCategories] = useState([]);
  const [tempColours, setTempColours] = useState([]);
  const [tempSizes, setTempSizes] = useState([]);
  const [tempPrice, setTempPrice] = useState(null);
  const [tempMinPrice, setTempMinPrice] = useState(null);

  const router = useRouter();
  const pathname = usePathname();
  const dispatch = useDispatch();

  const categoryImage = searchParams.get("category_image") || "";
  const swiperRef = useRef(null);

  // const selectedCategoryId = subcategoryId || categoryId || "";

  const selectedCategoryId =
    selectedCategories.length > 0 ? selectedCategories.join(",") : "";

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

  const category = useSelector((state) => state.master.categories);
  const all_products = useSelector((state) => state?.product?.allProducts);
  const appSetupdata = useSelector((state) => state.master.app_setup);
  const allsizes = useSelector((state) => state.master.allsizes);
  const allcolours = useSelector((state) => state.master.allcolours);
  const priceBounds = useSelector((state) => state.product.priceBounds);

  useEffect(() => {
    dispatch(appSetup());
    dispatch(getAllCategories());
    dispatch(getAllCOLOURS());
    dispatch(getAllSIZES());
  }, [dispatch]);

  const handlePageChange = (pageNumber) => {
    setOnPageChange(pageNumber);
  };

  useEffect(() => {
    if (priceBounds?.max && price === null) {
      setPrice(priceBounds.max);
      setMinPrice(priceBounds.min);
    }
  }, [priceBounds]);

  // const handleShow = () => {
  //   setShowFilter(true);
  // };

  const handleShow = () => {
    setTempCategories([...selectedCategories]);
    setTempColours([...selectedColours]);
    setTempSizes([...selectedSizes]);
    setTempPrice(price);
    setTempMinPrice(minPrice);
    setShowFilter(true);
  };

  const handleClose = () => {
    setShowFilter(false);
  };

  const applyProductFilters = async () => {
    const allCategoryIds = category?.map((c) => c.id) || [];

    // if every category is checked, treat it as "no filter" -> all products
    const isAllSelected =
      selectedCategories.length > 0 &&
      allCategoryIds.length > 0 &&
      allCategoryIds.every((id) => selectedCategories.includes(id));

    const categoryIdParam = isAllSelected ? "" : selectedCategories.join(",");

    await dispatch(
      getAllProducts({
        name: search,
        // category_id: selectedCategoryId || "",
        category_id: categoryIdParam,
        metal_id: selectedColours.join(","),
        size_id: selectedSizes.join(","),
        min_price: minPrice ?? "",
        max_price: price ?? "",
        page: onPageChange,
      }),
    );
  };

  useEffect(() => {
    if (!swiperRef.current || !category?.length) return;
    if (!selectedCategoryId) {
      swiperRef.current.slideTo(0);
      return;
    }

    const activeIndex = category.findIndex(
      (c) => Number(c.id) === Number(categoryId),
    );
    if (activeIndex !== -1) {
      // +1 because "All Product" slide is index 0
      swiperRef.current.slideTo(activeIndex + 1);
    }
  }, [category, selectedCategoryId]);

  const handleApplyFilters = () => {
    setSelectedCategories(tempCategories);
    setSelectedColours(tempColours);
    setSelectedSizes(tempSizes);
    setPrice(tempPrice);
    setMinPrice(tempMinPrice);
    setOnPageChange(1);
    setShowFilter(false);
  };

  useEffect(() => {
    if (priceBounds?.min == null || priceBounds?.max == null) return;
    applyProductFilters();
  }, [
    selectedCategories,
    dispatch,
    selectedColours,
    selectedSizes,
    price,
    search,
    onPageChange,
  ]);

  const handleResetFilters = () => {
    setTempCategories([]);
    setTempColours([]);
    setTempSizes([]);
    setTempPrice(priceBounds.max);
    setTempMinPrice(priceBounds.min);
  };

  const handleCategoryClick = (category_id) => {
    setSelectedCategories([Number(category_id)]);
    setSelectedSizes([]);
    setSelectedColours([]);
    setOnPageChange(1);
    const params = new URLSearchParams();
    params.set("category_id", category_id);
    if (categoryImage) params.set("category_image", categoryImage);
    router.replace(`${pathname}?${params.toString()}`, {
      scroll: false,
    });
  };

  useEffect(() => {
    setSelectedCategories(categoryId ? [Number(categoryId)] : []);
  }, [categoryId]);

  const handleAllProducts = () => {
    setSelectedCategories([]);
    setSelectedSizes([]);
    setSelectedColours([]);
    setPrice(priceBounds.max);
    setMinPrice(priceBounds.min);
    setOnPageChange(1);
    router.replace(pathname, {
      scroll: false,
    });
  };

  useEffect(() => {
    if (all_products && all_products.data) {
      setTotalPages(all_products.total_pages);
      setOnPageChange(all_products.current_page);
    }
  }, [all_products]);

  return (
    <section className="Categories_section_holder">
      {" "}
      <Breadcrumb_comp breadcrumbs={breadcrumbs} />
      <div className="container">
        <div className="Categories">
          <div className="heading_holder">
            <h4 className="heading_text">Explore Collection</h4>
          </div>

          <div className="cat_subcat_div">
            <div variant="pills" className="flex-row p-0 mb-3">
              <Swiper
                className="mySwiper pb-2"
                pagination={{
                  dynamicBullets: true,
                  clickable: true,
                }}
                onSwiper={(swiper) => {
                  swiperRef.current = swiper;
                }}
                modules={[Pagination, Navigation, Autoplay]}
                breakpoints={{
                  0: { slidesPerView: 2.5, spaceBetween: 10 },
                  350: { slidesPerView: 3, spaceBetween: 10 },
                  486: { slidesPerView: 3, spaceBetween: 10 },
                  576: { slidesPerView: 4, spaceBetween: 10 },
                  768: { slidesPerView: 6, spaceBetween: 10 },
                  992: { slidesPerView: 6, spaceBetween: 10 },
                  1200: { slidesPerView: 7, spaceBetween: 10 },
                  1300: { slidesPerView: 8, spaceBetween: 10 },
                }}
              >
                <SwiperSlide className="product-slide">
                  <Nav.Item>
                    <Nav.Link
                      // className={selectedCategoryId === "" ? "activecategory" : ""}
                      // onClick={() => handleCategoryClick("")}
                      className={
                        selectedCategoryId === "" ? "activecategory" : ""
                      }
                      onClick={handleAllProducts}
                    >
                      <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) => (
                  <SwiperSlide key={slide?.id} className="product-slide">
                    <Nav.Item>
                      <Nav.Link
                        className={
                          selectedCategories.includes(Number(slide?.id))
                            ? "activecategory"
                            : ""
                        }
                        onClick={() => 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>

          <div className="heading_holder">
            <h4 className="heading_text">Products</h4>
            <div className="mobile_filter_btn">
              <button onClick={handleShow} className="filter_btn">
                <FontAwesomeIcon icon={faFilter} /> Filter
              </button>
            </div>
          </div>

          <div className="row">
            {all_products?.data?.length > 0 ? (
              all_products.data.map((product, index) => {
                let metal, size, 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-3 col-md-4 col-sm-4 col-6 px-md-2 px-1 custom_5_col mb-2"
                    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 className="col-12">
                <div className="no_product_found">
                  <NoData />
                  <h3>No Products Found</h3>
                  <p>Try changing your filters or search.</p>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
      {all_products?.data?.length > 0 && (
        <div className="pagination_div">
          <Pagination_Holder
            onPageChange={onPageChange}
            totalPages={totalPages}
            handlePageChange={handlePageChange}
          />
        </div>
      )}
      <Filter_offcanvas
        show={showFilter}
        handleClose={handleClose}
        category={category}
        allsizes={allsizes}
        allcolours={allcolours}
        price={tempPrice}
        setPrice={setTempPrice}
        minPriceLimit={minPrice}
        selectedSizes={tempSizes}
        setSelectedSizes={setTempSizes}
        selectedColours={tempColours}
        setSelectedColours={setTempColours}
        selectedCategories={tempCategories}
        setSelectedCategories={setTempCategories}
        onApply={handleApplyFilters}
        onReset={handleResetFilters}
      />
    </section>
  );
}

export default Categories;
