"use client";
//import HeroCategory from "@/app/components/category/hero-category";
import ProductThumb from "@/app/components/cards/product-thumb";
import CategorySortBy from "@/app/components/category/category-sort";
import CategoryFilter from "@/app/components/category/category-filter";
import { useState } from "react";
import ToggleFilterButton from "../components/category/ToggleFilterButton";
import { usePersistentScroll } from "@/app/hook/usePersistentScroll";

interface Product {
  id: string;
  slug: string;
  main_item_image: {
    image_url: string;
  };
  design_house: {
    name: string;
  };
  product_name: string;
  price: number;
}

interface ProductFilter {
  id: string;
  name: string;
  options: Array<{
    value: string;
    label: string;
    checked: boolean;
  }>;
}

interface Pagination {
  current_page: number;
  per_page: number;
  total: number;
  last_page: number;
  from: number;
  to: number;
  next_page_url: string | null;
  prev_page_url: string | null;
}

interface CategoryClientProps {
  filterData: ProductFilter[];
  products: Product[];
  pagination: Pagination | null;
  initialQueryParams: Record<string, any>;
}

export default function CategoryClient({ 
  filterData,
  products: initialProducts,
  pagination: initialPagination,
  initialQueryParams
}: CategoryClientProps) {
  const [isSidebarShow, setIsSidebarShow] = useState(false);
  const [products, setProducts] = useState<Product[]>(initialProducts);
  const [pagination, setPagination] = useState<Pagination | null>(initialPagination);
  const [isLoadingMore, setIsLoadingMore] = useState(false);

  const toggleSidebar = () => {
    setIsSidebarShow((prev) => !prev);
    if (typeof window !== "undefined") {
      const scrollY = window.scrollY;
      try {
        localStorage.setItem("scrollY", scrollY.toString());
      } catch (err) {
        console.warn("[Category] Failed to persist scroll", err);
      }
    }
  };
  usePersistentScroll("category");

  const loadMoreProducts = async () => {
    if (!pagination?.next_page_url || isLoadingMore) return;

    setIsLoadingMore(true);
    try {
      const nextPage = pagination.current_page + 1;
      const queryParams = new URLSearchParams({
        ...initialQueryParams,
        page: nextPage.toString()
      });

      const response = await fetch(`/api/products?${queryParams.toString()}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      const result = await response.json();

      if (result?.success && result?.data?.product) {
        setProducts(prev => [...prev, ...result.data.product]);
        setPagination(result.data.pagination);
      }
    } catch (error) {
      console.error('[Category] Load more failed:', error);
    } finally {
      setIsLoadingMore(false);
    }
  };

  return (
    <div className="relative flex w-full flex-col">
      <div className="mob-noise absolute top-0 left-0 z-2 h-full w-full"></div>
    
      <div className="relative z-20 flex min-h-dvh flex-col">
        <div className="relative flex flex-col">
          <div className="sticky top-14 left-0 z-20 grid grid-cols-2 items-center justify-center py-0 gap-1 md:py-2 align-middle md:top-12 md:inline-flex md:flex-row">
            <ToggleFilterButton
              isOpenSideBar={isSidebarShow}
              onClick={toggleSidebar}
              totalItem={pagination?.total || products.length}
            />
            <CategorySortBy id="" />
          </div>
          <CategoryFilter
            isOpenSideBar={isSidebarShow}
            closeSidebar={() => setIsSidebarShow(false)}
            filterData={filterData}
          />

          <div
            className={`transition-all duration-300 ${
              isSidebarShow ? "ml-0 md:ml-80" : "ml-0"
            } min-h-screen flex-1`}
          >
            <div className="wrapper pt-14 md:pt-10">
              {products.length > 0 ? (
                <>
                  <div
                    className={`grid grid-cols-2 py-2 pb-10 lg:grid-cols-3 ${
                      isSidebarShow
                        ? "gap-10"
                        : "gap-4 md:gap-10 lg:gap-15 xl:gap-20"
                    }`}
                  >
                    {products.map((product: any) => (
                      <ProductThumb
                        key={product.id}
                        image={product.image}
                        hoverImg={product.hover_image}
                        title={product.product_name}
                        price={product.price}
                        url={`/product/${product.slug}`}
                        designHouse={product?.design_house}
                        pid={product.id}
                        showLikeBtn={true}
                        wishType="PRODUCT"
                      />
                    ))}
                  </div>
                  
                  {pagination && pagination.next_page_url && (
                    <div className="flex justify-center pb-20 pt-6">
                      <button
                        onClick={loadMoreProducts}
                        disabled={isLoadingMore}
                        className="group relative inline-flex items-center gap-2 px-8 py-3 font-medium text-black transition-all duration-300 hover:text-white disabled:cursor-not-allowed disabled:opacity-50"
                      >
                        <span className="absolute inset-0 border border-black transition-all duration-300 group-hover:bg-black group-disabled:border-gray-400"></span>
                        <span className="relative z-10">
                          {isLoadingMore ? (
                            <>
                              <svg
                                className="mr-2 inline h-4 w-4 animate-spin text-current"
                                xmlns="http://www.w3.org/2000/svg"
                                fill="none"
                                viewBox="0 0 24 24"
                              >
                                <circle
                                  className="opacity-25"
                                  cx="12"
                                  cy="12"
                                  r="10"
                                  stroke="currentColor"
                                  strokeWidth="4"
                                ></circle>
                                <path
                                  className="opacity-75"
                                  fill="currentColor"
                                  d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                                ></path>
                              </svg>
                              Loading...
                            </>
                          ) : (
                            <>
                              Load More
                              <span className="text-xs text-gray-600 group-hover:text-white/80">
                                ({pagination.to} of {pagination.total})
                              </span>
                            </>
                          )}
                        </span>
                      </button>
                    </div>
                  )}
                </>
              ) : (
                <div className="flex w-full flex-col items-center justify-center gap-2 py-20">
                  <h2>Product not found</h2>
                  <p className="text-sm">
                    Try adjusting your filters or searching again.
                  </p>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
