import { useEffect, React, useState } from "react";
import { useRouter } from "next/router";
import style from "./index.module.css";
import InputText from "@/components/utils/inputText";
import { CancelToken } from "axios";
import NextImage from "@/other/NextImage";
import ReactHtmlParser from "react-html-parser";
import moment from "moment";
import { customerApi } from "@/api/api";
import Loader from "@/components/utils/loader";

const BlogList = () => {
  const [posts, setPosts] = useState([]);
  const [tableData, setTableData] = useState({});
  const [loader, setLoader] = useState(true);
  const [page, setPage] = useState(1);
  const router = useRouter();
  const [search, setSearch] = useState("");

  let timer;
  const source = CancelToken.source();

  const loadData = async (loadPage, type) => {
    clearTimeout(timer);
    setLoader(true);
    if (type === "search") setPosts([]);
    timer = setTimeout(async () => {
      await customerApi
        .get("/blog/posts?limit=10&page=" + loadPage + "&search=" + search)
        .then((res) => {
          if (res.data.result && res.data.result.data.length > 0) {
            setTableData(res.data.result);
            if (type === "search") {
              setPosts(res.data.result.data);
            } else {
              setPosts((prev) => {
                let newArray = [...prev];
                newArray.push(...res.data.result.data);
                return newArray;
              });
            }
          } else {
            setPosts([]);
          }
          setLoader(false);
        })
        .then((err) => {
          console.log("err");
          setLoader(false);
        });
    }, 500);
  };

  useEffect(() => {
    setPage(1);
    loadData(1, "search");
    return () => clearTimeout(timer);
  }, [search]);

  return (
    <div className={`container ${style.blog_section}`}>
      <div className={style.search_bar}>
        <InputText
          placeholder="Search Posts"
          getValue={(value) => {
            setSearch(value);
          }}
          value={search}
          customCss={style.customSearch}
        />
      </div>
      {posts.length > 0 ? (
        <div className={style.post_section}>
          {posts.map((item, index) => (
            <div
              className={style.post_card}
              key={index}
              onClick={() => router.push(`/blog/${item._id}_${item.title}`)}
            >
              <div className={style.image_section}>
                <NextImage
                  src={
                    process.env.NEXT_PUBLIC_UPLOADS +
                    "/blogs/" +
                    item.normal_image
                  }
                  fill
                />
              </div>
              <div className={style.text_section}>
                <div className={style.head}>
                  <div className={style.title}>{item.title}</div>
                  <div className={style.date}>
                    {moment(item.created_at).format("DD MMM YYYY")}
                  </div>
                </div>
                <div className={style.subtitle}>{item.subtitle}</div>
              </div>
            </div>
          ))}

          {!loader && tableData.pageCount > page && (
            <div className={style.btnSection}>
              <div
                className={`teritary_btn`}
                onClick={() => {
                  setPage(page + 1);
                  loadData(page + 1, "");
                }}
              >
                Load More
              </div>
            </div>
          )}
        </div>
      ) : (
        !loader && <p className="exist_error">No Post Available</p>
      )}
      {loader && <Loader className={style.loader} />}
    </div>
  );
};

export default BlogList;
