import { useState } from "react";
import { Input } from "@arco-design/web-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 InputSearch = Input.Search;
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 onSearch = (value) => {
    setProjectList([]);
    setHasMore(true);
    setPage(1);
    fetchProjects(value, 1);
  };

  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 (searchValue = "", pageNum) => {
    try {
      const res = await getProjectsList({
        search: searchValue,
        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">
        <div className="project-library-search-area">
          <InputSearch
            className="ser-portfolio-search"
            onSearch={onSearch}
            searchButton="搜索"
          />
        </div>
        <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>
      <ProjectCasesModal
        data={modalData}
        visible={projectCasesModalVisible}
        onClose={handleCloseModal}
      />
    </div>
  );
};

export default ProjectLibrary;
