"use client";
import { useState, useEffect, useCallback } from "react";
import { useFilters } from "@/app/context/FilterContext";

export default function useCategoryProducts(initialProducts: any[] = []) {
  const { filters } = useFilters();
  const [products, setProducts] = useState<any[]>(initialProducts ?? []);
  const [page, setPage] = useState<number>(1);
  const [loading, setLoading] = useState<boolean>(false);

  const fetchProducts = useCallback(
    async (reset = false) => {
      try {
        setLoading(true);

        const params = new URLSearchParams({
          ...(filters || {}),
          page: reset ? "1" : String(page + 1),
        });

        const res = await fetch(`/api/products?${params}`);

        if (!res.ok) {
          throw new Error("Failed to fetch products");
        }

        const data = await res.json();

        const newProducts = Array.isArray(data?.products)
          ? data.products
          : [];

        if (reset) {
          setProducts(newProducts);
          setPage(1);
        } else {
          setProducts((prev) => [...prev, ...newProducts]);
          setPage((p) => p + 1);
        }

      } catch (error) {
        console.error("Product fetch error:", error);
      } finally {
        setLoading(false);
      }
    },
    [filters, page]
  );

  useEffect(() => {
    fetchProducts(true);
  }, [filters, fetchProducts]);

  return { products, loading, fetchProducts };
}