'use client';

import { useState } from 'react';
import Pagination from '@/components/layout/pagination';
import { getProducts } from '@/services/products';
import { IProductListProps } from './productList';
import ProductCard from '../productCard';

export default function ProductList({
  initialProducts,
  initialPagination,
  categoryId,
}: IProductListProps) {
  const [products, setProducts] = useState(initialProducts);
  const [pagination, setPagination] = useState(initialPagination);

  const fetchPage = (page: number) => {
    getProducts(categoryId, page)
      .then((res) => {
        setProducts(res.data);
        setPagination(res.pagination);

        document
          .getElementById('productList')
          ?.scrollIntoView({ behavior: 'smooth', block: 'start' });
      })
      .catch((error) => {
        console.error('Failed to fetch products:', error);
      });
  };

  return (
    <>
      <div className="grid gap-3 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
        {products.map((product, index) => (
          <ProductCard {...product} key={index} />
        ))}
      </div>
      <Pagination {...pagination} onPageChange={fetchPage} />
    </>
  );
}
