import React, { useState } from "react";
import { useProjectContext } from "../project/ProjectPage";
import {
  useActiveInActiveServiceProject,
  useServiceProjects,
} from "../../hooks/useServiceProject";
import { ITEMS_PER_PAGE } from "../../utils/constants";
import ProjectCard from "../../components/Project/ProjectCard";
import Pagination from "../../components/common/Pagination";
import GlobalModel from "../../components/common/GlobalModel";
import ManageServiceProject from "../../components/ServiceProject/ManageServiceProject";
import { SpinnerLoader } from "../../components/common/Loader";
import ServiceProjectCard from "../../components/ServiceProject/ServiceProjectTeam/ServiceProjectCard";

const ServiceProjectDisplay = ({ listView ,selectedStatuses }) => {
  const [currentPage, setCurrentPage] = useState(1);

  const { manageServiceProject, setManageServiceProject } = useProjectContext();
  const { data, isLoading, isError, error } = useServiceProjects(
    ITEMS_PER_PAGE,
    currentPage
  );
  const paginate = (page) => {
    if (page >= 1 && page <= (data?.totalPages ?? 1)) {
      setCurrentPage(page);
    }
  };

  const filteredProjects = data?.data?.filter(project =>
    selectedStatuses.includes(project?.status?.id)
  );

  if (isLoading)
    return (
      <div
        className="page-min-h d-flex justify-content-center align-items-center"
        style={{ minHeight: "80vh" }}
      >
        <SpinnerLoader />
      </div>
    );

  if (isError)
    return (
      <div className="page-min-h d-flex justify-content-center align-items-center">
        <p>{error.message}</p>
      </div>
    );
  return (
    <div className="row">
      {listView ? (
        <p>List</p>
      ) : (
        filteredProjects?.map((project) => (
          <ServiceProjectCard project={project} isCore={false} />
        ))

      )}

      <div className="col-12 d-flex justify-content-start mt-3">
        <Pagination
          currentPage={currentPage}
          totalPages={data?.totalPages}
          onPageChange={paginate}
        />
      </div>

      {manageServiceProject?.isOpen && (
        <GlobalModel
          size="md"
          isOpen={manageServiceProject?.isOpen}
          closeModal={() =>
            setManageServiceProject({ isOpen: false, project: null })
          }
        >
          <ManageServiceProject
            serviceProjectId={manageServiceProject?.project}
            onClose={() =>
              setManageServiceProject({ isOpen: false, project: null })
            }
          />
        </GlobalModel>
      )}
    </div>
  );
};

export default ServiceProjectDisplay;
