import React, { useState, useEffect, useMemo } from "react";
import CategorySection from "@/components/home/CategorySection";
import FilterSection from "@/components/Products/FilterSection";
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 { setFilteredProducts, setPagination } from "@/Redux/productFiltersSlice";
import { useRouter } from "next/router";
import Head from "next/head";
import Image from "next/image";
import debounce from "lodash/debounce";

export default function Product() {
  const { selectedCategory, selectedCategoryID } = useSelector(
    (state: RootState) => state.category
  );

  const dispatch = useDispatch();
  const router = useRouter();

  const [subcategoryData, setSubCategoryData] = React.useState<any[]>([]);
  const [brandData, setBrandData] = React.useState<any[]>([]);
  const [filteredBrandData, setFilteredBrandData] = React.useState(brandData);
  const [openMenu, setOpenMenu] = React.useState<boolean>(false);

  // State for each filter type
  const [selectedSubcategoryId, setSelectedSubcategoryId] = useState(null);
  const [selectedBrandId, setSelectedBrandId] = useState(null);
  const [selectedPriceRangeId, setSelectedPriceRangeId] = useState(null);
  const debouncedApplyFilters = useMemo(
    () => debounce(() => applyFilters(), 1000),
    [selectedSubcategoryId, selectedBrandId, selectedPriceRangeId, router.query.keyword, router.query.page]
  );


  // This useEffect calls debounced applyFilters whenever filters or query changes
  useEffect(() => {
    debouncedApplyFilters();

    // Cleanup on unmount or change
    return () => {
      debouncedApplyFilters.cancel();
    };
  }, [selectedSubcategoryId, selectedBrandId, selectedPriceRangeId, router.query.keyword, router.query.page]);

  // Handlers ONLY update state; remove applyFilters calls from here
  const handleSubcategoryChange = (id: any) => {
    setSelectedSubcategoryId(id);
  };

  const handleBrandChange = (id: any) => {
    setSelectedBrandId(id);
  };

  const handlePriceChange = (id: any) => {
    setSelectedPriceRangeId(id);
  };
  // This function applies all the filters together
  const applyFilters = async () => {
    try {
      let apiEndpoint = `https://api.jazzagain.com/public/index.php/api/getProducts?categoryId=${selectedCategoryID}`;

      if (selectedSubcategoryId) {
        apiEndpoint += `&subCategoryId=${selectedSubcategoryId}`;
      }
      if (selectedBrandId) {
        apiEndpoint += `&brandId=${selectedBrandId}`;
      }

      const currentPage = router.query.page || 1;

      if (router.query.keyword) {
        apiEndpoint = `https://api.jazzagain.com/public/index.php/api/getProducts?keyword=${router.query.keyword}&categoryId=${selectedCategoryID}&page=${currentPage}`;
      } else {
        apiEndpoint += `&page=${currentPage}`;
      }

      const searchResult = await axios.get(apiEndpoint);

      let filteredProducts = searchResult.data.products.data;

      if (selectedPriceRangeId) {
        const priceId = selectedPriceRangeId;

        if (priceId === `${selectedCategoryID}_1`) {
          filteredProducts = filteredProducts.filter((item: any) => item.productSellingPrice < 5001);
        } else if (priceId === `${selectedCategoryID}_2`) {
          filteredProducts = filteredProducts.filter(
            (item: any) => item.productSellingPrice >= 5001 && item.productSellingPrice <= 20000
          );
        } else if (priceId === `${selectedCategoryID}_3`) {
          filteredProducts = filteredProducts.filter((item: any) => item.productSellingPrice > 20000);
        }
      }

      dispatch(setFilteredProducts(filteredProducts));
      dispatch(setPagination(searchResult.data.products.pagination));

    } catch (error: any) {
      if (axios.isAxiosError(error)) {
        if (error.response?.status === 429) {
          console.warn("Too many requests – you're being rate-limited.");
        } else {
          console.error("API error:", error.response?.data || error.message);
        }
      } else {
        console.error("Unexpected error:", error);
      }
    }
  };



  // Handlers for each filter type
  // const handleSubcategoryChange = (id: any) => {
  //   setSelectedSubcategoryId(id);
  //   applyFilters();
  // };

  // const handleBrandChange = (id: any) => {
  //   setSelectedBrandId(id);
  //   applyFilters();
  // };

  // const handlePriceChange = async (id: any) => {
  //   setSelectedPriceRangeId(id);
  //   let apiEndpoint = `https://api.jazzagain.com/public/index.php/api/getProducts?categoryId=${selectedCategoryID}`;

  //   if (selectedSubcategoryId) {
  //     apiEndpoint += `&subCategoryId=${selectedSubcategoryId}&`;
  //   }
  //   if (selectedBrandId) {
  //     apiEndpoint += `brandId=${selectedBrandId}`;
  //   }
  //   if (router.query.keyword) {
  //     apiEndpoint = `https://api.jazzagain.com/public/index.php/api/getProducts?keyword=${router.query.keyword}&categoryId=${selectedCategoryID}`;
  //   }
  //   const searchResult = await axios.get(apiEndpoint);

  //   let newFilter = searchResult.data.products.data.filter((item: any) => {
  //     if (id == `${selectedCategoryID}_1`) {
  //       return item.productSellingPrice < 5001;
  //     } else if (id == `${selectedCategoryID}_2`) {
  //       return item.productSellingPrice >= 5001 && item.productSellingPrice <= 20000;
  //     } else {
  //       return item.productSellingPrice > 20001;
  //     }
  //   });
  //   dispatch(setFilteredProducts(newFilter));
  // };

  React.useEffect(() => {
    const getCatgeory = async () => {
      try {
        const getbrands = await axios.get(
          `https://api.jazzagain.com/public/index.php/api/getBrands?categoryId=${selectedCategoryID}`
        );
        const subCategories = await axios.get(
          `https://api.jazzagain.com/public/index.php/api/getSubCategories/${selectedCategoryID}`
        );

        setBrandData(getbrands.data.brands);
        setFilteredBrandData(getbrands.data.brands);
        setSubCategoryData(subCategories.data.subCategories);
      } catch (error) {
        console.error("Error:", error);
      }
    };
    getCatgeory();
  }, [selectedCategory, selectedCategoryID]);

  // React.useEffect(() => {
  //   applyFilters();
  // }, [selectedSubcategoryId, selectedBrandId, selectedPriceRangeId]);

  const handleMenubar = () => {
    setOpenMenu(!openMenu);
  };
  // React.useEffect(() => {
  //   applyFilters();
  // }, [router.query.page, router.query.keyword]);

  return (
    <>
      <Head>
        <script
          id='my-custom-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', '408374148405242');
                fbq('track', 'ViewContent');
              `,
          }}
        />
        <noscript>
          <img
            height="1"
            width="1"
            style={{ display: "none" }}
            src="https://www.facebook.com/tr?id=408374148405242&ev=ViewContent&noscript=1"
            alt="facebook pixel"
          />
        </noscript>
        <title>
          {selectedCategory
            ? `${selectedCategory} | Second-hand Clothes | JazzAgain`
            : "Second-hand Clothes | Affordable Pre-owned Clothing | JazzAgain"}
        </title>
        <meta
          name="description"
          content={
            selectedCategory
              ? `Shop ${selectedCategory} second-hand clothes at JazzAgain. Find affordable pre-owned clothing, vintage fashion, and gently used branded clothes.`
              : "Shop affordable second-hand clothes, vintage fashion, and gently used branded clothes at JazzAgain. Discover sustainable fashion and pre-loved clothing online."
          }
        />
        <meta
          name="keywords"
          content="Pre-owned clothes online, Buy second-hand clothes, Thrift store online, Affordable used clothing, Sustainable fashion, Online thrift shop, Vintage second-hand clothing, Pre-loved clothes for sale, Gently used clothing deals, Second-hand branded clothes, Best places to buy used clothes online, Affordable second-hand designer clothes, Where to find vintage clothing online, Second-hand clothes in Nigeria, Pre-owned clothing stores near me"
        />
        <link rel="canonical" href="https://jazzagain.com/product" />
        <meta name="robots" content="index, follow" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta property="og:title" content="Second-hand Clothes | JazzAgain" />
        <meta
          property="og:description"
          content="Shop affordable second-hand clothes, vintage fashion, and gently used branded clothes at JazzAgain. Discover sustainable fashion and pre-loved clothing online."
        />
        <meta property="og:image" content="/images/jazzagian-logo.png" />
        <meta property="og:url" content="https://jazzagain.com/product" />
        <meta property="og:type" content="website" />
        <meta name="twitter:card" content="summary_large_image" />
        <meta name="twitter:title" content="Second-hand Clothes | JazzAgain" />
        <meta
          name="twitter:description"
          content="Shop affordable second-hand clothes, vintage fashion, and gently used branded clothes at JazzAgain. Discover sustainable fashion and pre-loved clothing online."
        />
        <meta name="twitter:image" content="/images/jazzagian-logo.png" />
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{
            __html: `
              {
                "@context": "https://schema.org",
                "@type": "Product",
                "name": "${selectedCategory || "Second-hand Clothes"}",
                "description": "Shop affordable second-hand clothes, vintage fashion, and gently used branded clothes at JazzAgain. Discover sustainable fashion and pre-loved clothing online.",
                "image": "/images/jazzagian-logo.png",
                "offers": {
                  "@type": "Offer",
                  "priceCurrency": "NGN",
                  "price": "0",
                  "availability": "https://schema.org/InStock"
                }
              }
            `,
          }}
        />
      </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">
                <FilterSection
                  title="SUB CATEGORIES"
                  items={subcategoryData.map((item) => {
                    return { id: item._id, title: item.subCategoryName };
                  })}
                  onFilterChange={handleSubcategoryChange}
                />
              </div>

              <div className="py-2">
                <FilterSection
                  title="ALL BRANDS"
                  items={filteredBrandData.map((item) => {
                    return { id: item._id, title: item.brandName };
                  })}
                  onFilterChange={handleBrandChange}
                />
              </div>
              <div className="py-2">
                <FilterSection
                  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">
              <FilterSection
                title="SUB CATEGORIES"
                items={subcategoryData.map((item) => {
                  return { id: item._id, title: item.subCategoryName };
                })}
                onFilterChange={handleSubcategoryChange}
              />
            </div>

            <div className="py-1">
              <FilterSection
                title="ALL BRANDS"
                items={filteredBrandData.map((item) => {
                  return { id: item._id, title: item.brandName };
                })}
                onFilterChange={handleBrandChange}
              />
            </div>

            <div className="py-1">
              <FilterSection
                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 />
          </div>
        </div>
      </div>
    </>
  );
}