import React from "react";
import styles from "@/styles/common/small.module.css";
import axios from "axios";
import { useRouter } from "next/router";
import toast, { Toaster } from "react-hot-toast";
import { useSelector, useDispatch } from "react-redux";
import { RootState } from "@/Redux/store";
import FavoritesIcon from "../helpers/FavoritesIcon";
import {
  setProducts,
  setFilteredProducts,
  setPagination,
  setFeaturedPagination,
} from "@/Redux/productFiltersSlice";
import { ConfigProvider, Skeleton } from "antd";
import { Pagination as AntPagination } from "antd";
import { formatNumberWithCommas } from "../commonFunctions/formatNumberWithCommas";
import { userActivity } from "../commonFunctions/userActivity";

const FeaturedProductSection: React.FC = () => {
  const router = useRouter();
  const dispatch = useDispatch();

  const selectedCategory = useSelector((state: RootState) => state.category);
  const AllProducts = useSelector((state: RootState) => state.productFilter); //isme data sahi nhi set hora
  const pagination = useSelector(
    (state: RootState) => state.productFilter.pagination
  );
  const featuredpagination = useSelector(
    (state: RootState) => state.productFilter.featuredpagination
  );
  const subCategory = useSelector(
    (state: RootState) => state.productFilter.subcategories
  );
  const _loggedIn_user = useSelector((state: RootState) => state.user.user);
  const [loading, setLoading] = React.useState<boolean>(false);
  const [page, setPage] = React.useState(1);
  const LoadingImages = [0, 1, 2, 3, 4, 5];

  const handleItemClick = (itemId: string) => {

    
    router.push(`/singleproduct/${itemId}`);
  };
  const handlePageChange = async (page: number) => {
    setPage(page);
    setLoading(true);
    try {
      let allProducts: any[] = [];

      let testD;

      const response = await axios.get(
        `https://api.jazzagain.com/public/index.php/api/getFeaturedProducts?page=${page}`
      );
      const productsData = response.data;
      allProducts = allProducts.concat(productsData.products.data);
      testD = response.data.products.pagination;
      let addPagination = {
        total: testD.total,
        count: testD.count,
        per_page: testD.per_page,
        current_page: testD.current_page,
        total_pages: testD.total_pages,
        from: testD.from,
        to: testD.to,
      };
      // Assuming setFilteredProducts and setProducts actions expect an array of products
      dispatch(setFilteredProducts(allProducts));
      dispatch(setProducts(allProducts));
      dispatch(setFeaturedPagination(addPagination));
      setLoading(false);
    } catch (error) {
      console.error("Error fetching all products:", error);
    }
  };
  return loading ? (
    <div className="grid grid-cols-2 text-xs sm:text-base sm:grid-cols-2 lg:grid-cols-3 justify-center">
      {LoadingImages.map((i) => {
        return (
          <div className="m-3" key={i}>
            <Skeleton.Image active style={{ height: 200, width: 250 }} />
            <Skeleton.Input
              active
              size="small"
              className="my-2"
              style={{ width: 250 }}
            />
          </div>
        );
      })}
    </div>
  ) : (
    <>
      <div className="grid grid-cols-2 bg-[#E5E4E5] text-xs sm:text-base sm:grid-cols-2 lg:grid-cols-3 justify-center">
        <Toaster
          toastOptions={{
            className: "",
            duration: 5000,
          }}
        />
        {AllProducts.filteredProducts.length === 0 ? (
          <div className="grid col-span-3 text-center h-[30vh] p-10">
            <h2 className="mt-2 text-lg font-semibold px-3 text-gray-800">
              No Product Found !
            </h2>
            <p className="mt-1 text-gray-600 px-3">
              Sorry, we couldn&apos;t find any products that match your search.
            </p>
          </div>
        ) : (
          AllProducts.filteredProducts.map((item: any, index: number) => {
            return (
              <div
                key={index}
                className="w-[95%] mx-auto m-[.5rem] cursor-pointer"
                onClick={() => handleItemClick(item._id)}
              >
                <div
                  style={{
                    backgroundImage: `url(https://api.jazzagain.com/public/${item?.productFeaturedImage})`,
                  }}
                  className={` w-[100%] aspect-[2/1.2] rounded-md bg-cover bg-center bg-no-repeat flex flex-row-reverse`}
                >
                  <div
                    className={"p-1 h-6 bg-[#FF332B] text-xs sm:text-sm text-white flex items-center justify-center ".concat(
                      styles.borderRounded
                    )}
                  >
                    <span className="flex">
                      <span className="px-1">&#8358;</span>{" "}
                      <span>
                        {formatNumberWithCommas(item?.productSellingPrice)}
                      </span>
                    </span>

                    <span className="flex pl-1 text-xs">
                      <span>-</span>{" "}
                      <span>{item?.productDiscountPercentage}</span>
                      <span> %</span>
                    </span>
                  </div>
                </div>
                <div className="flex justify-between">
                  <div className="m-1 font-semibold">
                    <p>{item?.productTitle}</p>
                    <p className="text-xs text-gray-600">
                      Location - {item?.seller?.city?.name},{" "}
                      {item?.seller?.state?.name}
                    </p>
                  </div>
                  <div className="">
                    <FavoritesIcon itemId={item?._id} />
                  </div>
                </div>
              </div>
            );
          })
        )}
      </div>
      <div className="text-center m-6">
        <ConfigProvider
          theme={{
            components: {
              Pagination: {
                itemSize: 40,
                itemInputBg: "#FF332B",
              },
            },
          }}
        >
        </ConfigProvider>
      </div>
    </>
  );
};

export default FeaturedProductSection;
