import React, { useState, useEffect } from "react";
import axios from "axios";
import { useDispatch, useSelector } from "react-redux";
import { useRouter } from "next/router";
import Head from "next/head";
import Image from "next/image";
import { RxCross2 } from "react-icons/rx";
import CategorySection from "@/components/home/CategorySection";
import ProductSection from "@/components/Products/ProductSection";
import ViewallFilterSection from "@/components/Products/ViewallFilterSection";
import { RootState } from "@/Redux/store";
import { setFilteredProducts, setPagination } from "@/Redux/productFiltersSlice";

export default function Product() {
  const { selectedCategory, selectedCategoryID } = useSelector(
    (state: RootState) => state.category
  );
  const filteredProducts = useSelector(
    (state: RootState) => state.productFilter.filteredProducts
  );

  const dispatch = useDispatch();
  const router = useRouter();

  const [brandData, setBrandData] = useState<any[]>([]);
  const [filteredBrandData, setFilteredBrandData] = useState<any[]>([]);
  const [subcategoryData, setSubCategoryData] = useState<any[]>([]);
  const [openMenu, setOpenMenu] = useState<boolean>(false);
  const [selectedPriceRangeId, setSelectedPriceRangeId] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [perPage, setPerPage] = useState<number>(10);
  const [lastPage, setLastPage] = useState<number>(1);

  const applyFilters = async (page: number = currentPage) => {
    const apiEndpoint = `https://api.jazzagain.com/public/index.php/api/getLatestProducts?page=${page}`;
    const searchResult = await axios.get(apiEndpoint);

    if (selectedPriceRangeId) {
      handlePriceChange(selectedPriceRangeId, page);
    } else {
      dispatch(setFilteredProducts(searchResult.data.products.data));
      dispatch(setPagination(searchResult.data.products.pagination));
    }

    setPerPage(searchResult.data.products.per_page);
    setLastPage(searchResult.data.products.last_page);
  };

  const handlePriceChange = async (id: string | null, page: number = currentPage) => {
    setSelectedPriceRangeId(id);
    const apiEndpoint = `https://api.jazzagain.com/public/index.php/api/getLatestProducts?page=${page}`;
    const searchResult = await axios.get(apiEndpoint);

    const newFilter = searchResult.data.products.data.filter((item: any) => {
      if (id === `${selectedCategoryID}_1`) {
        return item.productSellingPrice < 5000;
      } else if (id === `${selectedCategoryID}_2`) {
        return item.productSellingPrice >= 5001 && item.productSellingPrice <= 20000;
      } else {
        return item.productSellingPrice > 20001;
      }
    });

    dispatch(setFilteredProducts(newFilter));
    setPerPage(searchResult.data.products.per_page);
    setLastPage(searchResult.data.products.last_page);
  };

  useEffect(() => {
    const fetchCategoryData = async () => {
      try {
        const [brandsResponse, subCategoriesResponse] = await Promise.all([
          axios.get(`https://api.jazzagain.com/public/index.php/api/getBrands?categoryId=${selectedCategoryID}`),
          axios.get(`https://api.jazzagain.com/public/index.php/api/getSubCategories/${selectedCategoryID}`),
        ]);

        setBrandData(brandsResponse.data.brands);
        setFilteredBrandData(brandsResponse.data.brands);
        setSubCategoryData(subCategoriesResponse.data.subCategories);
      } catch (error) {
        console.error("Error fetching category data:", error);
      }
    };

    fetchCategoryData();
  }, [selectedCategory, selectedCategoryID]);

  useEffect(() => {
    applyFilters();
  }, [selectedPriceRangeId, currentPage]);

  const toggleMenu = () => {
    setOpenMenu(!openMenu);
  };

  const goToPreviousPage = () => {
    if (currentPage > 1) {
      setCurrentPage(currentPage - 1);
    }
  };

  const goToNextPage = () => {
    if (currentPage < lastPage) {
      setCurrentPage(currentPage + 1);
    }
  };

  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', 'latest');
            `,
          }}
        />
        <noscript>
          <Image
            height={1}
            width={1}
            alt="facebook link"
            style={{ display: "none" }}
            src="https://www.facebook.com/tr?id=360254480441103&ev=latest&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={toggleMenu}
            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="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"
            style={{ boxShadow: "1px 0px 55px -9px #585353c9" }}
          >
            <button
              className="float-right mr-[-4px] text-[#FF332B]"
              onClick={toggleMenu}
            >
              <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">
          <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}
              />
            </div>
          </div>

          <div className="w-[97%] lg:w-[80%]">
            <ProductSection />
            <div className="flex justify-between mt-4">
              <button
                onClick={goToPreviousPage}
                disabled={currentPage === 1}
                className="bg-[#FF332B] text-white px-4 py-2 rounded mx-2 disabled:opacity-50"
              >
                Previous
              </button>
              <button
                onClick={goToNextPage}
                disabled={currentPage === lastPage}
                className="bg-[#FF332B] text-white px-4 py-2 rounded mx-2 disabled:opacity-50"
              >
                Next
              </button>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}