import React, { useEffect, useState } from "react";
import { Nav, Tab } from "react-bootstrap";
import { useDispatch, useSelector } from "react-redux";
import { useLocation, useParams } from "react-router-dom";
import { getAllProducts } from "../../features/products/productsSlice";
import All_Products_Category_Slider from "../product_details/all_products_category_slider/All_Products_Category_Slider";
import { getAllChildCategory } from "../../features/master/masterSlice";
import Product_Info_Card from "../common-components/product_info_card/Product_Info_Card";
import Breadcrumb_comp from "../common-components/breadcrumb-comp/Breadcrumb_comp";
import Shop_By_Shape from "../home/shop_by_shape/Shop_By_Shape";
import { variant_type } from "../../utils/common";

const Product_Listing_Page_ChildCategory = () => {
  const [selectedOption, setSelectedOption] = useState(null);
  const location = useLocation();
  const [subCategoryId, setSubCategoryId] = useState(null);
  const searchParams = new URLSearchParams(location.search);
  const categoryName = searchParams.get("category_name");
  const subcategory_id = searchParams.get("sub_category_id");
  const categoryImage = searchParams.get("category_image");
  const subcategoryname = searchParams.get("subcategory_name");

  const { id } = useParams();
  const dispatch = useDispatch();
  const queryParams = new URLSearchParams(location.search);
  const searchValue = queryParams.get("search");
  useEffect(() => {
    setSubCategoryId(id);
    dispatch(
      getAllProducts({
        name: searchValue,
        // category_id: id,
        subcategory_id: subcategory_id,
        childcategory_id: id,
        priceOrder: selectedOption || "",
      }),
    );
  }, [dispatch, id]);
  const allProducts = useSelector((state) => state.product.allProducts);
  useEffect(() => {
    dispatch(
      getAllProducts({
        name: searchValue,
        // category_id: id,
        subcategory_id: subcategory_id,
        childcategory_id: subCategoryId,
        priceOrder: selectedOption || "",
      }),
    );
  }, [dispatch, selectedOption, searchValue, subCategoryId]);

  const childcategoriesData = useSelector(
    (state) => state.master.childcategories,
  );

  useEffect(() => {
    dispatch(getAllChildCategory({ subcategory_id }));
  }, [dispatch, id]);

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

  return (
    <section className="Product_Listing_Page ">
      <Tab.Container id="left-tabs-example" defaultActiveKey="Grid">
        <Breadcrumb_comp breadcrumbs={breadcrumbs} />
        <Shop_By_Shape />

        <div className="container">
          {/* Show SubCategory Slider only if not searching */}
          {/* {!searchValue && ( */}
          <All_Products_Category_Slider
            categoryImage={categoryImage}
            subcategoryname={subcategoryname}
            categoryId={id}
            show={true}
            subcategory_id={id}
            categories={childcategoriesData}
            setSubCategoryId={setSubCategoryId}
            subCategoryId={subCategoryId}
          />
          {/* )} */}

          <div className="row">
            {allProducts?.data?.length > 0 ? (
              allProducts?.data?.map((product) => {
                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">
                    <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={metal?.Metal?.name}
                      savingPrice={
                        parseFloat(activeVariant?.mrp || 0) -
                        parseFloat(activeVariant?.price || 0)
                      }
                    />
                  </div>
                );
              })
            ) : (
              <div
                style={{
                  textAlign: "center",
                  padding: "20px",
                  fontWeight: "bold",
                  width: "100%",
                  color: "#000",
                }}
              >
                Product Not Available
              </div>
            )}
          </div>
        </div>
      </Tab.Container>
    </section>
  );
};

export default Product_Listing_Page_ChildCategory;
