import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { jobAPI, interviewAPI, studentAPI } from "@/services/api";
import { mapJobList, mapInterviewList } from "@/utils/dataMapper";
import JobList from "./components/JobList";

import "./index.css";

const CompanyJobsPage = () => {
  const [jobs, setJobs] = useState([]);
  const [interviews, setInterviews] = useState([]);
  const [loading, setLoading] = useState(true);
  const [isExpand, setIsExpand] = useState(false); // 是否展开

  const navigate = useNavigate();

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    try {
      setLoading(true);
      
      // Get current user's student ID from API
      let studentId = null;
      try {
        const currentStudent = await studentAPI.getCurrentStudent();
        studentId = currentStudent?.id;
      } catch (err) {
        console.log('Could not get current student:', err);
      }
      
      // Fetch jobs (and interviews if we have a student ID)
      const jobsData = await jobAPI.getList({ 
        page: 1, 
        pageSize: 10, 
        isActive: true 
      });
      
      let interviewsData = { data: [] };
      if (studentId) {
        try {
          interviewsData = await interviewAPI.getList({ 
            studentId: studentId,
            status: 'SCHEDULED'
          });
        } catch (err) {
          console.log('No interviews found or API error');
        }
      }
      
      // Map data to frontend format
      const mappedJobs = mapJobList(jobsData.data || jobsData);
      const mappedInterviews = mapInterviewList(interviewsData.data || interviewsData);
      
      setJobs(mappedJobs);
      setInterviews(mappedInterviews);
    } catch (error) {
      console.error("Failed to fetch data:", error);
      // Fallback to empty data
      setJobs([]);
      setInterviews([]);
    } finally {
      setLoading(false);
    }
  };

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

  if (loading) {
    return (
      <div className="company-jobs-page-wrapper">
        <div className="company-jobs-page" style={{ justifyContent: 'center', alignItems: 'center' }}>
          <p>加载中...</p>
        </div>
      </div>
    );
  }

  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>
          <div className="company-jobs-page-left-list-wrapper">
            <JobList
              data={jobs}
              backgroundColor="#F7F8FA"
            />
          </div>
        </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>
            <ul className="company-jobs-page-interview-list">
              {interviews.length > 0 ? 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>
              )) : (
                <li className="company-jobs-page-interview-item">
                  <p style={{ color: '#999', textAlign: 'center', width: '100%' }}>
                    暂无面试安排
                  </p>
                </li>
              )}
            </ul>
          </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;
