"use client";

import Loader from "@/components/loaders/Loader";
import { useBlogQuery } from "@/services/hooks/blog";
import { useEffect, useRef } from "react";
import CardBlog from "./CardBlog";

type ListOfBlogProps = {
  searchKeyword?: string;
};

export default function ListOfBlog({ searchKeyword }: ListOfBlogProps) {
  const pageRef = useRef(1);
  const blogQuery = useBlogQuery();

  useEffect(() => {
    blogQuery._fetch({
      search: searchKeyword,
      page: pageRef.current,
    });
  }, []);

  function fetchMore() {
    blogQuery._fetch({
      search: searchKeyword,
      page: ++pageRef.current,
    });
  }

  return (
    <>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mt-5">
        {blogQuery.data.map((blog) => (
          <CardBlog key={blog.slug} data={blog} />
        ))}
      </div>
      <div className="mt-5">
        {blogQuery.isFetching && <Loader />}
        {!blogQuery.isFetching && blogQuery.hasNext && (
          <button onClick={fetchMore} className="button button-primary">
            LOAD MORE...
          </button>
        )}
      </div>
    </>
  );
}
