import React, { useState } from "react";
import CategorySection from "@/components/home/CategorySection";
import ProductSection from "@/components/Products/ProductSection";
import axios from "axios";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/Redux/store";
import { RxCross2 } from "react-icons/rx";
import ViewallFilterSection from "@/components/Products/ViewallFilterSection";
import { setFilteredProducts, setPagination, setProducts } from "@/Redux/productFiltersSlice";
import Head from "next/head";
import Image from "next/image";

export default function Product() {
  const { selectedCategory, selectedCategoryID } = useSelector(
    (state: RootState) => state.category
  );

  const dispatch = useDispatch();
  const [openMenu, setOpenMenu] = React.useState<boolean>(false);
  const [selectedPriceRangeId, setSelectedPriceRangeId] = useState(null); 


  const applyFilters = async () => {
    try {
      let allProducts :any = [];
      let currentPage = 1;
      let lastPage = 0;
  
      do {
        const response = await axios.get(`https://api.jazzagain.com/public/index.php/api/getRecomendedProducts?page=${currentPage}`);
        console.log(response.data)
        const productsData = response.data.products.data; // Assume this is the array of products
  
        // Add fetched products to the allProducts array
        allProducts = allProducts.concat(productsData);
  
        currentPage = response.data.products.current_page + 1;
        lastPage = response.data.products.last_page;
      } while (currentPage <= lastPage);

      console.log(allProducts)
  
      // Now, filter the allProducts if selectedPriceRangeId is set
      if (selectedPriceRangeId) {
        allProducts = allProducts.filter((product:any) => {
          switch (selectedPriceRangeId) {
            case `${selectedCategoryID}_1`:
              return product.productSellingPrice < 5000;
            case `${selectedCategoryID}_2`:
              return product.productSellingPrice >= 5001 && product.productSellingPrice <= 20000;
            case `${selectedCategoryID}_3`:
              return product.productSellingPrice > 20001;
            default:
              return true;
          }
        });
      }
  
      // Dispatch the filtered (or all) products to your Redux store
      dispatch(setFilteredProducts(allProducts));
      // If you're using a separate action to set all products without filtering, you might want to conditionally dispatch it
      // e.g., only if no price range is selected
      if (!selectedPriceRangeId) {
        dispatch(setProducts(allProducts));
      }
    } catch (error) {
      console.error("Error fetching all products:", error);
    }
  };
  

React.useEffect(() => {
  applyFilters();
}, [selectedPriceRangeId]);

  const handleMenubar = () => {
    setOpenMenu(!openMenu);
  };

  const handlePriceChange = async (id: any) => {
    // Toggle filter off if the same filter is selected again
    if (selectedPriceRangeId === id) {
      setSelectedPriceRangeId(null);
      applyFilters(); // Call without filter
    } else {
      setSelectedPriceRangeId(id);
      // Filtering logic is part of applyFilters or directly here before setting state
      applyFilters(); // Call with the new filter id
    }
  };
  

  return (
    <>
    <Head><link rel="shortcut icon" href="/images/jazzagian-logo.png" />
        <script
          dangerouslySetInnerHTML={{
            __html: `
              !function(f,b,e,v,n,t,s)
              {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
              n.callMethod.apply(n,arguments):n.queue.push(arguments)};
              if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
              n.queue=[];t=b.createElement(e);t.async=!0;
              t.src=v;s=b.getElementsByTagName(e)[0];
              s.parentNode.insertBefore(t,s)}(window, document,'script',
              'https://connect.facebook.net/en_US/fbevents.js');
              fbq('init', '360254480441103');
              fbq('track', 'Recommended Product');
            `,
          }}
        />
        <noscript>
          <Image
            height="1"
            width="1"
            alt="facebook link"
            style={{ display: 'none' }}
            src="https://www.facebook.com/tr?id=360254480441103&ev=Recommendedproduct&noscript=1"
          />
        </noscript>
      </Head>


    <div className="relative mt-[.8rem]">
      <CategorySection />
      <div className="flex justify-between flex-row-reverse text-[#FF332B] w-[60%] mx-auto py-4">
        <div
          onClick={handleMenubar}
          className="bg-[#FF332B] rounded text-white p-1 px-3 lg:hidden cursor-pointer"
        >
          Filters
        </div>
      </div>
      <hr className="border border-gray-500 w-[60%] mx-auto mb-[1.5rem]" />

      {/* sidebar for small screen */}
      {openMenu && (
        <>
          <div
            className={
              openMenu
                ? "lg:hidden absolute w-[85%] left-0 sm:w-[50%] bg-white px-8 max-h-screen overflow-y-auto rounded py-3 my-3 transition-all duration-300"
                : "left-[-100%] transition-all duration-300"
            }
            style={{
              boxShadow: "1px 0px 55px -9px #585353c9",
            }}
          >
            <button
              className="float-right mr-[-4px] text-[#FF332B]"
              onClick={handleMenubar}
            >
              <RxCross2 size={30} />
            </button>
            <br />
            <br />
            
            {/* <div className="py-2">
              <ViewallFilterSection
                title="SUB CATEGORIES"
                items={subcategoryData.map((item) => {
                  return { id: item._id, title: item.subCategoryName };
                  // <option value={item._id}>{item.categoryName}</option>
                })}
              />
            </div>
            <div className="py-2">
              <ViewallFilterSection
                title="ALL BRANDS"
                items={filteredBrandData.map((item) => {
                  return { id: item._id, title: item.brandName };
                  // <option value={item._id}>{item.categoryName}</option>
                })}
              />
            </div> */}
            <div className="py-2">
              <ViewallFilterSection
                title="PRICE"
                subText="choose from options"
                items={[
                  { id: `${selectedCategoryID}_1`, title: "0-5000" },
                { id: `${selectedCategoryID}_2`, title: "5000-20000" },
                { id: `${selectedCategoryID}_3`, title: "Above 20000" },
                ]}
                onFilterChange={handlePriceChange}
              />
            </div>

          </div>
        </>
      )}

      <div className="w-[85%] mx-auto flex justify-center ">
        {/* sidebar for lg screen */}
        <div className="hidden lg:w-[20%] lg:block">

          {/* <div className="py-1">
            <ViewallFilterSection
              title="SUB CATEGORIES"
              items={subcategoryData.map((item) => {
                return { id: item._id, title: item.subCategoryName };
              })}
            />
          </div>

          <div className="py-1">
            <ViewallFilterSection
              title="ALL BRANDS"
              items={filteredBrandData.map((item) => {
                return { id: item._id, title: item.brandName };
              })}
            />
          </div> */}

          <div className="py-1">
            <ViewallFilterSection
              title="PRICE"
              subText="choose from options"
              items={[
                { id: `${selectedCategoryID}_1`, title: "0-5000" },
                { id: `${selectedCategoryID}_2`, title: "5000-20000" },
                { id: `${selectedCategoryID}_3`, title: "Above 20000" },
              ]}
              onFilterChange={handlePriceChange}
            />
          </div>
        </div>

        <div className="w-[97%] lg:w-[80%]">
          <ProductSection />
          {/* <RecommendedCards/> */}
        </div>
      </div>
    </div>
    </>
  );
}
