import { useState, useCallback } from "react";
import { useNavigate } from "react-router-dom";
import JobList from "@/pages/CompanyJobsPage/components/JobList";
import InfiniteScroll from "@/components/InfiniteScroll";
import { getJobsList } from "@/services";

import "./index.css";

const PAGE_SIZE = 20;

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

  // 返回到企业内推岗位页面
  const handleBack = () => {
    navigate("/company-jobs");
  };

  const fetchJobs = useCallback(async () => {
    const res = await getJobsList({
      page: listPage,
      pageSize: PAGE_SIZE,
      isActive: true,
    });
    if (res.success) {
      // Mock数据已经是前端格式，不需要映射
      setJobs((prevList) => {
        const newList = [...prevList, ...res.data];
        if (res.total === newList?.length) {
          setListHasMore(false);
        } else {
          setListPage((prevPage) => prevPage + 1);
        }
        return newList;
      });
    }
  }, [listPage]);

  return (
    <div className="company-jobs-list-page">
      {/* 返回按钮 */}
      <div className="back-button-wrapper">
        <button className="back-button" onClick={handleBack}>
          <span className="back-icon">←</span>
          <span className="back-text">返回</span>
        </button>
      </div>
      
      <InfiniteScroll
        loadMore={fetchJobs}
        hasMore={listHasMore}
        empty={jobs.length === 0}
        className="company-jobs-list-page-wrapper"
      >
        <JobList data={jobs} className="jobs-list-margin" />
      </InfiniteScroll>
    </div>
  );
};

export default CompanyJobsListPage;
