import { useState } from "react";
import { useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { mapJobList, mapInterviewList } from "@/utils/dataMapper";
import JobList from "./components/JobList";
import { getJobsList, getInterviewsList } from "@/services";
import InfiniteScroll from "@/components/InfiniteScroll";

import "./index.css";
const PAGE_SIZE = 10;

const CompanyJobsPage = () => {
  const studentInfo = useSelector((state) => state.student.studentInfo);
  const [isExpand, setIsExpand] = useState(false); // 是否展开
  const [jobs, setJobs] = useState([]);
  const [jobsListPage, setJobsListPage] = useState(1);
  const [joblistHasMore, setJobsListHasMore] = useState(true);
  const [interviews, setInterviews] = useState([]);
  const [interviewsPage, setInterviewsPage] = useState(1);
  const [interviewsHasMore, setInterviewsHasMore] = useState(true);
  const navigate = useNavigate();

  // 获取面试信息
  const fetchInterviewsData = async () => {
    try {
      if (studentInfo?.id) {
        const res = await getInterviewsList({
          page: interviewsPage,
          pageSize: PAGE_SIZE,
          studentId: studentInfo?.id,
          status: "SCHEDULED",
        });
        if (res.success) {
          const mappedInterviews = mapInterviewList(res.data || []);
          setInterviews((prevList) => {
            const newList = [...prevList, ...mappedInterviews];
            if (res.total === newList?.length) {
              setInterviewsHasMore(false);
            } else {
              setInterviewsPage((prevPage) => prevPage + 1);
            }
            return newList;
          });
        }
      }
    } catch (error) {
      console.error("Failed to fetch data:", error);
      setInterviews([]);
    }
  };

  // 获取企业内推岗位
  const fetchJobsList = async () => {
    try {
      const res = await getJobsList({
        page: jobsListPage,
        pageSize: PAGE_SIZE,
        isActive: true,
      });
      if (res.success) {
        const mappedJobs = mapJobList(res.data);
        setJobs((prevList) => {
          const newList = [...prevList, ...mappedJobs];
          if (res.total === newList?.length) {
            setJobsListHasMore(false);
          } else {
            setJobsListPage((prevPage) => prevPage + 1);
          }
          return newList;
        });
      }
    } catch (error) {
      console.error("Failed to fetch data:", error);
      setJobs([]);
    }
  };

  const handleJobWrapperClick = () => {
    navigate("/company-jobs-list");
  };

  return (
    <div className="company-jobs-page-wrapper">
      <div className="company-jobs-page">
        <div className="company-jobs-page-left" onClick={handleJobWrapperClick}>
          <p className="company-jobs-page-title">企业内推岗位库</p>
          <InfiniteScroll
            loadMore={fetchJobsList}
            hasMore={joblistHasMore}
            className="company-jobs-page-left-list-wrapper"
          >
            <JobList data={jobs} backgroundColor="#F7F8FA" />
          </InfiniteScroll>
        </div>
        <div className="company-jobs-page-interview-wrapper">
          <div
            className={`${
              isExpand
                ? "company-jobs-page-interview"
                : "company-jobs-page-interview company-jobs-page-interview-expand"
            }`}
          >
            <p className="company-jobs-page-title">内推岗位面试</p>
            <InfiniteScroll
              loadMore={fetchInterviewsData}
              hasMore={interviewsHasMore}
              className="company-jobs-page-interview-list"
            >
              {interviews.map((item) => (
                <li className="company-jobs-page-interview-item" key={item.id}>
                  <div className="company-jobs-page-interview-item-info">
                    <p className="company-jobs-page-interview-item-info-position">
                      {item.position}
                    </p>
                    {item.job?.tags?.length > 0 ? (
                      <ul className="company-jobs-page-interview-item-info-tags">
                        {item.job.tags.map((tag) => (
                          <li
                            className="company-jobs-page-interview-item-info-tag"
                            key={tag}
                          >
                            {tag}
                          </li>
                        ))}
                      </ul>
                    ) : null}
                    <span className="company-jobs-page-interview-item-info-salary">
                      {item.job?.salary || "面议"}
                    </span>
                  </div>
                  <div className="company-jobs-page-interview-item-btn-wrapper">
                    <span>{item.interviewTime}</span>
                    <div
                      className={`company-jobs-page-interview-item-btn ${
                        item.status !== "COMPLETED" &&
                        "company-jobs-page-interview-item-btn-active"
                      }`}
                    >
                      {item.statusText}
                    </div>
                  </div>
                </li>
              ))}
            </InfiniteScroll>
          </div>
        </div>
        <div
          className={
            isExpand
              ? "company-jobs-page-process-wrapper-expand"
              : "company-jobs-page-process-wrapper-close"
          }
        >
          <div
            className="company-jobs-page-process-wrapper-title"
            onClick={() => setIsExpand(!isExpand)}
          >
            岗位陪跑流程
          </div>
          <div className="company-jobs-page-process-content">
            <div className="company-jobs-page-process-item-icon icon1">
              <p>内推岗位简历投递</p>
            </div>
            <div className="company-jobs-page-process-item-round-dot icon2" />
            <div className="company-jobs-page-process-item-icon icon3">
              <p>岗位简历接收</p>
            </div>
            <div className="company-jobs-page-process-item-icon icon4">
              <p>面试时间地点确定</p>
            </div>
            <div className="company-jobs-page-process-item-icon icon5">
              <p>参与企业面试</p>
            </div>
            <div className="company-jobs-page-process-item-round-dot icon6" />
            <div className="company-jobs-page-process-item-icon icon7">
              <p>企业offer发送</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default CompanyJobsPage;
