import { useState } from "react";
import toast from "@/components/Toast";
import InfiniteScroll from "@/components/InfiniteScroll";
import ProjectCasesModal from "./components/ProjectCasesModal";
import { getProjectsList, getProjectsdetail } from "@/services/projectLibrary";
import "./index.css";


const PAGE_SIZE = 10;

const ProjectLibrary = () => {
  const [modalData, setModalData] = useState(undefined);
  const [projectList, setProjectList] = useState([]);
  const [projectCasesModalVisible, setProjectCasesModalVisible] =
    useState(false);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);



  const handleProjectClick = async (item) => {
    if (item?.id) {
      const res = await getProjectsdetail(item.id);
      if (res.success) {
        setModalData(res.data);
        setProjectCasesModalVisible(true);
      } else {
        toast.error(res.message);
      }
    } else {
      toast.error("加载数据失败，请刷新重试");
    }
  };

  const handleCloseModal = () => {
    setProjectCasesModalVisible(false);
    setModalData(undefined);
  };

  const fetchProjects = async (pageNum) => {
    try {
      const res = await getProjectsList({
        page: pageNum ?? page,
        pageSize: PAGE_SIZE,
      });
      if (res.success) {
        setProjectList((prevList) => {
          const newList = [...prevList, ...res.data];
          if (res.total === newList?.length) {
            setHasMore(false);
          } else {
            setPage((prevPage) => prevPage + 1);
          }
          return newList;
        });
      }
    } catch (error) {
      console.error("Failed to fetch projects:", error);
    }
  };

  return (
    <div className="project-library-page">
      <div className="project-library-wrapper">
        <p className="project-library-title">文旅班级项目库</p>
        <InfiniteScroll
          loadMore={fetchProjects}
          hasMore={hasMore}
          empty={projectList.length === 0}
          className="project-library-list"
        >
          {projectList.map((item) => (
            <li className="project-library-item" key={item.id}>
              <p className="project-library-item-title">{item.description}</p>
              <div>
                <p>{item.name}</p>
                <span onClick={() => handleProjectClick(item)}>详情 &gt;</span>
              </div>
            </li>
          ))}
        </InfiniteScroll>
      </div>
      
      {/* 我的项目库板块 */}
      <div className="project-library-wrapper my-project-library">
        <p className="project-library-title">我完成的项目库</p>
        <div className="project-library-empty">
          <p>暂无项目</p>
        </div>
      </div>
      
      <ProjectCasesModal
        data={modalData}
        visible={projectCasesModalVisible}
        onClose={handleCloseModal}
      />
    </div>
  );
};

export default ProjectLibrary;
