import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { getJobsList } from "@/services";
import { mapJobList } from "@/utils/dataMapper";
import JobList from "@/pages/CompanyJobsPage/components/JobList";

import "./index.css";

const CompanyJobsListPage = () => {
  const [jobs, setJobs] = useState([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const navigate = useNavigate();

  useEffect(() => {
    fetchJobs();
  }, [page]);

  const fetchJobs = async () => {
    try {
      setLoading(true);
      const response = await getJobsList({
        page,
        pageSize: 20,
        isActive: true,
      });

      const mappedJobs = mapJobList(response.data || response);
      setJobs(mappedJobs);
      setTotal(response.total || mappedJobs.length);
    } catch (error) {
      console.error("Failed to fetch jobs:", error);
      setJobs([]);
    } finally {
      setLoading(false);
    }
  };

  if (loading && jobs.length === 0) {
    return (
      <div
        className="company-jobs-list-page-wrapper"
        style={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          minHeight: "400px",
        }}
      >
        <p>加载中...</p>
      </div>
    );
  }

  return (
    <ul className="company-jobs-list-page-wrapper">
      <JobList data={jobs} />
      {jobs.length === 0 && !loading && (
        <div
          style={{
            textAlign: "center",
            padding: "40px",
            color: "#999",
          }}
        >
          暂无岗位信息
        </div>
      )}
    </ul>
  );
};

export default CompanyJobsListPage;
