import React, { useEffect, useState } from "react";
import CategorySection from "@/components/home/CategorySection";
import ProductSection from "@/components/Products/ProductSection";
import axios from "axios";
import { useRouter } from "next/router";
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, setProducts } from "@/Redux/productFiltersSlice";
import Head from "next/head";
import FeaturedProductSection from "@/components/Products/FeaturedProductSection";
import Image from "next/image";
import { ApiBaseUrl } from "@/interceptor/instance";

export default function Product() {
  const { selectedCategory, selectedCategoryID } = useSelector(
    (state: RootState) => state.category
  );
  const router = useRouter();
  const dispatch = useDispatch();
  const [openMenu, setOpenMenu] = React.useState<boolean>(false);
  const [selectedPriceRangeId, setSelectedPriceRangeId] = useState(null);
  const [states, setStates] = useState<any[]>([]);
  const [cities, setCities] = useState<any[]>([]);
  const [selectedStateId, setSelectedStateId] = useState<any>();
  const [selectedCity, setSelectedCity] = useState<string | null>(null);

  const handleMenubar = () => {
    setOpenMenu(!openMenu);
  };

  //fetch all products
  const applyFilters = async () => {
    try {
      let allProducts: any = [];
      let currentPage = 1;
      let lastPage = 0;

      do {
        const response = await axios.get(
          `${ApiBaseUrl}/api/getFeaturedProducts?page=${currentPage}`
        );
        const productsData = response.data.products.data;
        allProducts = allProducts.concat(productsData);
        currentPage = response.data.products.current_page + 1;
        lastPage = response.data.products.last_page;
      } while (currentPage <= lastPage);

      // filter by selectedPriceRange
      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;
          }
        });
      }

      // filter by selectedStateId
      if (selectedStateId) {
        allProducts = allProducts.filter((product: any) => {
          console.log({ selectedStateId });
          return product.seller.stateId === selectedStateId;
        });
      }

      dispatch(setFilteredProducts(allProducts));
      if (!selectedPriceRangeId && !selectedCity && !selectedStateId) {
        dispatch(setProducts(allProducts));
      }
    } catch (error) {
      console.error("Error fetching all products:", error);
    }
  };

  const handlePriceChange = (id: any) => {
    if (selectedPriceRangeId === id) {
      setSelectedPriceRangeId(null);
    } else {
      setSelectedPriceRangeId(id);
    }
  };

  const handleStateClick = async (id: string) => {
    setSelectedStateId(id);
    applyFilters();
  };

  React.useEffect(() => {
    //fetch states
    const fetchStates = async () => {
      try {
        const response = await axios.get(
          `${ApiBaseUrl}/api/getCountryStates/160`
        );
        setStates(response.data.states);
      } catch (error) {
        console.log("Error fetching states", error);
      }
    };
    fetchStates();
    applyFilters();
  }, [selectedPriceRangeId, selectedCity, selectedStateId]);

  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', 'Featured');
            `,
          }}
        />
        <noscript>
          <Image
            height="1"
            width="1"
            alt="facebook link"
            style={{ display: "none" }}
            src="https://www.facebook.com/tr?id=360254480441103&ev=Featured&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]" />

        {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="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="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}
              />
              {/* State Filter */}
              <ViewallFilterSection
                title="STATE"
                subText="choose from states"
                items={states.map((state) => ({
                  id: state._id,
                  title: state.name,
                }))}
                onFilterChange={(stateId: any) => handleStateClick(stateId)}
              />

              {/* City Filter (based on selected state) */}
              {/* <ViewallFilterSection
                title="CITY"
                subText="choose from cities"
                items={cities.map((city) => ({
                  id: city._id,
                  title: city.name,
                }))}
                onFilterChange={(city) => setSelectedCity(city)}
              /> */}
            </div>
          </div>

          <div className="w-[97%] lg:w-[80%]">
            {router.route === "/product/featured" ? (
              <FeaturedProductSection />
            ) : (
              <ProductSection />
            )}
          </div>
        </div>
      </div>
    </>
  );
}
