'use client'

import React, {useEffect, useState} from 'react'
import ProductItem from './productItem';
import Pagination from '../components/pagination'
import http from '../components/http';


//const fetcher = (...args) => fetch(...args).then((response) => response.json());


export default function ProductList({params}) {

  const query = params?.query || '';
  const category = params?.category || '';
  const price = params?.price || '';
  const city = params?.city || '';
  const [product, setProduct] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);


  useEffect(() => {
    const fetchProducts = async () => {
     try{
      const res = await http.get(`search/product?query=${query}&category=${category}`);
    // const res = await fetch('api/products');
    //const res = await http.get(`product`);

     console.log(res.data)
     // const data = await res.json();
    //  console.log(res.data)
      setProduct(res.data);
     } 
     catch (err){
      console.log(err)

     }
    };

    fetchProducts();
  }, [query,category, city])
 console.log(product)

  //pagination
  const recordsPerPage = 20;
  const lastIndex = currentPage * recordsPerPage;
  const firstIndex = lastIndex - recordsPerPage;
  const orders = product.slice(firstIndex, lastIndex);

  const paginate = (n) => setCurrentPage(n);


 // let url = productUrlEndpoint + `?query=${query}?category=${category}`

  console.log( price, city, category)
  //console.log(url)

 // const { isLoading, data: product, error } = useSWR(url, fetcher);
 // if (isLoading) return <p>{"data is loading"}</p>;
 // if (error) return <p>{"Error in Connection"}</p>;
 // console.log(product)

  return (
    <>
    {product &&
        orders.map((p, key) => {
    return<li>
 
           <ProductItem list={p} key={key} />
    
</li>})}

<br/>
<Pagination
        order={product.length}
        recordsPerPage={recordsPerPage}
        paginate={paginate}/>
        
</>
  )
}
