"use client";
import { useState } from "react";
import Pagination from "../components/pagination";
import PostItem from "./postItem";
import useSWR from "swr";
import { postUrlEndpoint } from "../components/http";

{
  /*function getBlogs() {
  //Imitate Delay
  await new Promise((resolve) => setTimeout(resolve, 3000));

  const endPoint = "https://api.eventsplc.com/api/post";

  const res = await fetch(endPoint, {
    next: {
      revalidate: 60 * 60,
    },
  });
  return res.json();
}
*/
}
const fetcher = (...args) => fetch(...args).then((response) => response.json());

function PostsList(props) {
  const [currentPage, setCurrentPage] = useState(1);
  const { isLoading, data: posts, error } = useSWR(postUrlEndpoint, fetcher);
  if (isLoading) return <p>{"data is loading"}</p>;
  if (error) return <p>{"Error in Connection"}</p>;

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

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

  return (
    <>
      <div className="-mx-4 flex flex-wrap">
        <PostItem list={orders} />
      </div>
      <Pagination
        order={posts.length}
        recordsPerPage={recordsPerPage}
        paginate={paginate}
      />
    </>
  );
}

export default PostsList;
