import { useState, useCallback } from "react";
import JobList from "@/pages/CompanyJobsPage/components/JobList";
import InfiniteScroll from "@/components/InfiniteScroll";
import { getJobsList } from "@/services";
import { mapJobList } from "@/utils/dataMapper";
import "./index.css";

const PAGE_SIZE = 20;

const CompanyJobsListPage = () => {
  const [jobs, setJobs] = useState([]);
  const [listPage, setListPage] = useState(1);
  const [listHasMore, setListHasMore] = useState(true);

  const fetchJobs = useCallback(async () => {
    const res = await getJobsList({
      page: listPage,
      pageSize: PAGE_SIZE,
      isActive: true,
    });
    if (res.success) {
      const mappedJobs = mapJobList(res.data);
      setJobs((prevList) => {
        const newList = [...prevList, ...mappedJobs];
        if (res.total === newList?.length) {
          setListHasMore(false);
        } else {
          setListPage((prevPage) => prevPage + 1);
        }
        return newList;
      });
    }
  }, [listPage]);

  return (
    <InfiniteScroll
      loadMore={fetchJobs}
      hasMore={listHasMore}
      empty={jobs.length === 0}
      className="company-jobs-list-page-wrapper"
    >
      <JobList data={jobs} className="jobs-list-margin" />
    </InfiniteScroll>
  );
};

export default CompanyJobsListPage;
