"use client";

import React, { useEffect, useRef, useState, useCallback } from "react";
import "./CollectionSection.css";
import { FaChevronDown, FaChevronUp } from "react-icons/fa";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import useApi from "@/hooks/useApi";
import { CiBoxList, CiGrid41 } from "react-icons/ci";
import DropDown from "../DropDown/DropDown";
import HorizontalSlider from "../HorizontalSlider/HorizontalSlider";
import ProductCardGrid from "../ProductCardGrid/ProductCardGrid";
import ProductCardList from "../ProductCardList/ProductCardList";
import Loader from "../Loader/Loader";
import { sortBySequence } from "@/utils/helpers";
import { useAuth } from "@/Context/AuthContext";
import { useLocation } from "@/Context/LocationContext";
import InfiniteScroll from "react-infinite-scroll-component";
import CustomLoader from "../CustomLoader/CustomLoader";
import { baseURL } from "@/utils/constant";
import { cartImage } from "@/utils/mediaConstant";
import { getImageUrl } from "@/utils/imageUrl";

// Skeleton Components
const ProductCardGridSkeleton = () => (
  <div className="animate-pulse bg-white rounded-lg p-3">
    <div className="w-full h-48 bg-gray-200 rounded mb-3"></div>
    <div className="h-4 bg-gray-200 rounded w-3/4 mb-2"></div>
    <div className="h-4 bg-gray-200 rounded w-1/2"></div>
    <div className="h-6 bg-gray-200 rounded w-1/3 mt-2"></div>
  </div>
);

const ProductCardListSkeleton = () => (
  <div className="flex flex-row border p-4 space-x-4 bg-white animate-pulse">
    <div className="w-32 h-32 md:w-64 md:h-64 bg-gray-200 rounded"></div>
    <div className="flex-1 space-y-3">
      <div className="h-6 bg-gray-200 rounded w-3/4"></div>
      <div className="h-4 bg-gray-200 rounded w-1/2"></div>
      <div className="h-8 bg-gray-200 rounded w-1/3"></div>
    </div>
  </div>
);

const CollectionSection = () => {
  const { get, post, put, del, loading, error } = useApi();
  const { mainCategories, subCategories, superSubCategories } = useAuth();
  const { location } = useLocation();
  const [changeView, setChangeView] = useState(true);
  const [subCategory, setSubCategory] = useState({});
  const params = useParams();
  console.log("🔍 useParams() se kya mila:", params);

  const [isOpen, setIsOpen] = useState(true);
  const [visibleCount, setVisibleCount] = useState(10);
  const [products, setProducts] = useState([]);
  const [sliderCategories, setSliderCategories] = useState([]);
  const [limitedProducts, setLimitedProducts] = useState([]);
  const [isProductsLoading, setIsProductsLoading] = useState(false);
  const [productCount, setProductCount] = useState(19);
  const [currentPage, setCurrentPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [sortValue, setSortValue] = useState("");
  const [isSortModalOpen, setIsSortModalOpen] = useState(false);
  const buttonRef = useRef(null);
  const dropdownRef = useRef(null);
  const [itemsLength, setItemsLength] = useState();
  const [isFetchingMore, setIsFetchingMore] = useState(false);
  const [searchInfo, setSearchInfo] = useState(null);
  const scrollableContainerRef = useRef(null);
  const [initialLoadComplete, setInitialLoadComplete] = useState(false);

  const toggleDropdown = () => {
    setIsSortModalOpen(!isSortModalOpen);
  };

  // Close the dropdown if clicked outside of it
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target) &&
        buttonRef.current &&
        !buttonRef.current.contains(event.target)
      ) {
        setIsSortModalOpen(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  // Reset products when location or sort changes
  useEffect(() => {
    if (params?.collectionType) {
      setProducts([]);
      setCurrentPage(1);
      setHasMore(true);
      setInitialLoadComplete(false);
      fetchProducts(1);
      
      if (scrollableContainerRef.current) {
        scrollableContainerRef.current.scrollTop = 0;
      }
    }
  }, [params?.collectionType, sortValue, location?.cityId, location?.city, location?.country]);

  const fetchProducts = async (page = 1) => {
    setIsProductsLoading(true);
    try {
      const currentCityId = location?.cityId || localStorage.getItem("user_city_id") || "";
      const currentCity = location?.cleanCity || location?.city || "";
      const currentCountry = location?.country || localStorage.getItem("user_country") || "";

      const paramsObj = {
        collectionName: params?.collectionType,
        page: page,
        sortValue: sortValue,
        limit: 10
      };

      if (currentCityId) {
        paramsObj.cityId = currentCityId;
      } else if (currentCity) {
        paramsObj.city = currentCity;
      }

      if (currentCountry) {
        paramsObj.country = currentCountry;
      }

      const queryString = new URLSearchParams(paramsObj).toString();
      const apiUrl = `product/getCollectionProductByPage?${queryString}`;
      
      const { data } = await get(apiUrl);
      
      setProducts(data?.products || []);
      setHeadingTitle(data?.title || "New Arrivals");
      setSearchInfo(data?.searchInfo || null);
      
      if (data?.hasMore !== undefined) {
        setHasMore(data.hasMore);
      } else {
        setHasMore(data?.products?.length > 0);
      }
      
      setCurrentPage(data?.currentPage || page);
      setItemsLength(data?.itemLength || 0);
      setInitialLoadComplete(true);
      
    } catch (error) {
      console.log("❌ API Error Details:", {
        message: error.message,
        response: error.response,
        status: error.response?.status
      });
      setProducts([]);
      setHasMore(false);
      setInitialLoadComplete(true);
    } finally {
      setIsProductsLoading(false);
    }
  };

  const fetchMoreProducts = useCallback(async () => {
    if (!hasMore || isFetchingMore) return;

    setIsFetchingMore(true);
    const nextPage = currentPage + 1;

    try {
      const currentCityId = location?.cityId || localStorage.getItem("user_city_id") || "";
      const currentCity = location?.cleanCity || location?.city || "";
      const currentCountry = location?.country || localStorage.getItem("user_country") || "";

      const paramsObj = {
        collectionName: params?.collectionType,
        page: nextPage,
        sortValue: sortValue,
        limit: 10
      };

      if (currentCityId) {
        paramsObj.cityId = currentCityId;
      } else if (currentCity) {
        paramsObj.city = currentCity;
      }

      if (currentCountry) {
        paramsObj.country = currentCountry;
      }

      const queryString = new URLSearchParams(paramsObj).toString();
      const apiUrl = `product/getCollectionProductByPage?${queryString}`;

      const { data } = await get(apiUrl);

      const newProducts = data?.products || [];
      
      const existingProductIds = new Set(products.map(p => p._id));
      const uniqueNewProducts = newProducts.filter(p => !existingProductIds.has(p._id));

      if (uniqueNewProducts.length > 0) {
        setProducts((prevItems) => [...prevItems, ...uniqueNewProducts]);
        setHasMore(data?.hasMore || false);
        setCurrentPage(nextPage);
        setSearchInfo(data?.searchInfo || searchInfo);
      } else {
        setHasMore(false);
      }
    } catch (error) {
      console.log(error);
      setHasMore(false);
    } finally {
      setIsFetchingMore(false);
    }
  }, [currentPage, hasMore, isFetchingMore, params?.collectionType, sortValue, location?.cityId, location?.city, location?.country, products.length, searchInfo]);

  const sidebarMainCategories = mainCategories?.sort(
    (a, b) => a?.sequence - b?.sequence
  );

  const sidebarSubCategories = subCategories?.sort(
    (a, b) => a?.sequence - b?.sequence
  );
  const sidebarSuperSubCategories = superSubCategories?.sort(
    (a, b) => a?.sequence - b?.sequence
  );
  
  const [dataType, setDataType] = useState("");
  const [headingTitle, setHeadingTitle] = useState("");
  const [categoryDetails, setCategoryDetails] = useState({});
  const [expandedCategory, setExpandedCategory] = useState(null);
  const [expandedSubcategory, setExpandedSubcategory] = useState(null);

  // Render skeleton loaders for initial load
  const renderSkeletons = () => {
    const skeletons = [];
    const skeletonCount = changeView ? 8 : 3; // Grid mein 8, list mein 3 skeletons
    
    for (let i = 0; i < skeletonCount; i++) {
      skeletons.push(
        changeView ? 
          <ProductCardGridSkeleton key={`skeleton-${i}`} /> : 
          <ProductCardListSkeleton key={`skeleton-${i}`} />
      );
    }
    
    return changeView ? (
      <div className="grid grid-cols-2 gap-4 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-4">
        {skeletons}
      </div>
    ) : (
      <div className="flex flex-col space-y-4">
        {skeletons}
      </div>
    );
  };

  // Render loader for infinite scroll (single loader)
  const renderInfiniteScrollLoader = () => {
    if (!isFetchingMore) return null;
    
    return (
      <div className="flex justify-center items-center py-8">
        <CustomLoader />
      </div>
    );
  };

  return (
    <div 
      ref={scrollableContainerRef}
      id="scrollable-collection-container"
      className="h-screen overflow-y-auto hide-scrollbar bg-gray-100"
      style={{ height: '100vh' }}
    >
      <div className="px-4 md:px-20 py-16">
        <div>
          <div className="flex justify-between md:flex-col lg:flex-col lg:items-stretch sm:items-center md:items-stretch">
            <div className="lg:mb-4 md:mb-4 mb-0 flex items-center">
              <h1 className="lg:text-[35px] md:text-3xl sm:text-lg font-pMedium">
                {headingTitle}
              </h1>
            </div>

            <div className="flex md:justify-between lg:justify-between justify-end items-center px-0 py-4 lg:p-4 md:py-4 ">
            
 <div className="text-black p-2 rounded sm:mr-2">
                {products?.length} items
             
              </div>

              <div className="flex space-x-4">
                <div>
                  <button
                    onClick={() => setChangeView(!changeView)}
                    className="bg-white text-black flex items-center py-[10px] px-2 space-x-2"
                    disabled={isProductsLoading}
                  >
                    {changeView ? (
                      <CiBoxList className="text-black" />
                    ) : (
                      <CiGrid41 className="text-black" />
                    )}
                    <p className="text-sm text-black font-osRegular hidden md:block">
                      {changeView ? "View as List" : "View as Grid"}
                    </p>
                  </button>
                </div>

                <div className="hidden md:block">
                  <div className="relative inline-block text-left">
                    <button
                      onClick={toggleDropdown}
                      className={`bg-white text-black flex items-center py-3 px-2 ${
                        sortValue ? "space-x-4" : "space-x-20"
                      } `}
                      ref={buttonRef}
                      disabled={isProductsLoading}
                    >
                      <p className="text-xs font-osRegular text-gray-400">
                        Sort by{" "}
                        <span className="font-osBold text-black">
                          {sortValue}
                        </span>
                      </p>
                      <FaChevronDown className="text-black" />
                    </button>

                    {isSortModalOpen && (
                      <div
                        className="absolute right-0 mt-[1px] z-10 bg-white border border-gray-200 shadow-lg rounded"
                        ref={dropdownRef}
                        style={{ width: buttonRef.current?.offsetWidth }}
                      >
                        <ul>
                          <li
                            className="px-4 py-2 font-osRegular hover:bg-gray-100 cursor-pointer text-xs"
                            onClick={() => {
                              setSortValue("Price: Low to High");
                              toggleDropdown();
                            }}
                          >
                            Price: Low to High
                          </li>
                          <li
                            className="px-4 py-2 font-osRegular hover:bg-gray-100 cursor-pointer text-xs"
                            onClick={() => {
                              setSortValue("Price: High to Low");
                              toggleDropdown();
                            }}
                          >
                            Price: High to Low
                          </li>
                          <li
                            className="px-4 py-2 font-osRegular hover:bg-gray-100 cursor-pointer text-xs"
                            onClick={() => {
                              setSortValue("Name: Ascending");
                              toggleDropdown();
                            }}
                          >
                            Name: Ascending
                          </li>
                          <li
                            className="px-4 py-2 font-osRegular hover:bg-gray-100 cursor-pointer text-xs"
                            onClick={() => {
                              setSortValue("Name: Descending");
                              toggleDropdown();
                            }}
                          >
                            Name: Descending
                          </li>
                        </ul>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          {/* Products Section with InfiniteScroll */}
          <div className="mt-4">
            <InfiniteScroll
              dataLength={products?.length}
              next={fetchMoreProducts}
              hasMore={hasMore}
              loader={renderInfiniteScrollLoader()}
              scrollableTarget="scrollable-collection-container"
            >
              {/* Show skeletons during initial load */}
              {!initialLoadComplete && isProductsLoading ? (
                renderSkeletons()
              ) : products?.length > 0 ? (
                changeView ? (
                  // Grid View
                  <div className="grid grid-cols-2 gap-4 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-4 items-center justify-center">
                    {products?.map((item) => (
                      <ProductCardGrid
                        key={item?._id}
                        productName={item?.productName}
                        productPrice={item?.productPrice}
                        salePrice={item?.salePrice}
                        customImageStyles={"md:w-96 md:h-48"}
                        customImgTagStyles={"md:w-96 md:h-48 object-fill"}
                        customStyles={"max-w-96 max-h-96"}
                        productImage={
                          item?.productImages?.length
                            ? getImageUrl(item?.productImages?.[0])
                            : cartImage 
                        }
                        productId={item?._id}
                        productMainCatId={item?.mainCategoryId}
                        productSubCatId={item?.subCategoryId}
                        productSuperSubCatId={item?.superSubCategoryId}
                        sellerId={item?.sellerId}
                        alias={item?.alias}
                        packageName={item?.packageName}
                      />
                    ))}
                  </div>
                ) : (
                  // List View
                  <div className="flex flex-col space-y-4">
                    {products?.map((item) => (
                      <ProductCardList
                        key={item?._id}
                        productName={item?.productName}
                        salePrice={item?.salePrice}
                        productPrice={item?.productPrice}
                        productImage={
                          item?.productImages?.length
                            ? getImageUrl(item?.productImages?.[0])
                            : cartImage 
                        }
                        productId={item?._id}
                        productMainCatId={item?.mainCategoryId}
                        productSubCatId={item?.subCategoryId}
                        productSuperSubCatId={item?.superSubCategoryId}
                        sellerId={item?.sellerId}
                        alias={item?.alias}
                        packageName={item?.packageName}
                      />
                    ))}
                  </div>
                )
              ) : (
                // No Products
                initialLoadComplete && !isProductsLoading && (
                  <div className="text-center py-20">
                    <p className="text-gray-500">No products found</p>
                  </div>
                )
              )}
            </InfiniteScroll>
          </div>
        </div>
      </div>
    </div>
  );
};

export default CollectionSection;