import React, { useEffect, useState } from "react";
import ProjectListView from "../../components/Project/ProjectListView";
import ProjectCardView from "../../components/Project/ProjectCardView";
import GlobalModel from "../../components/common/GlobalModel";
import ManageServiceProject from "../../components/ServiceProject/ManageServiceProject";
import { useProjectContext } from "./ProjectPage";
import { SpinnerLoader } from "../../components/common/Loader";
import { useProjects } from "../../hooks/useProjects";
import { useServiceProjects } from "../../hooks/useServiceProject";
import { ITEMS_PER_PAGE, PROJECT_STATUS } from "../../utils/constants";
import usePagination from "../../hooks/usePagination";
import ManageProjectInfo from "../../components/Project/ManageProjectInfo";

const ProjectsDisplay = ({
  listView,
  searchTerm,
  selectedStatuses,
  handleStatusChange,
}) => {
  const [currentPage, setCurrentPage] = useState(1);
  const {
    manageProject,
    manageServiceProject,
    setMangeProject,
    setManageServiceProject,
  } = useProjectContext();

  const [projectList, setProjectList] = useState([]);

  const { data, isLoading, isError, error } = useProjects(ITEMS_PER_PAGE, 1);

  const filteredProjects =
    data?.data?.filter((project) => {
      const statusId =
        project.projectStatusId ?? project?.status?.id ?? project?.statusId;

      const matchesStatus = selectedStatuses.includes(statusId);

      const matchesSearch = project?.name
        ?.toLowerCase()
        ?.includes(searchTerm?.toLowerCase());

      return matchesStatus && matchesSearch;
    }) ?? [];

  const paginate = (page) => {
    if (page >= 1 && page <= (data?.totalPages ?? 1)) {
      setCurrentPage(page);
    }
  };

  const sortingProject = (projects) => {
    if (!isLoading && Array.isArray(projects)) {
      const grouped = {};

      projects.forEach((project) => {
        const statusId = project.projectStatusId ?? project?.status?.id;
        if (!grouped[statusId]) grouped[statusId] = [];
        grouped[statusId].push(project);
      });

      const sortedGrouped = selectedStatuses
        .filter((statusId) => grouped[statusId])
        .flatMap((statusId) =>
          grouped[statusId].sort((a, b) =>
            a?.name?.toLowerCase()?.localeCompare(b?.name?.toLowerCase())
          )
        );

      setProjectList((prev) => {
        const isSame = JSON.stringify(prev) === JSON.stringify(sortedGrouped);
        return isSame ? prev : sortedGrouped;
      });
    }
  };

  useEffect(() => {
    if (!isLoading && data?.data) {
      sortingProject(data.data);
    }
  }, [data?.data, isLoading, selectedStatuses]);

  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 ? (
        <ProjectListView
          data={projectList}
          currentPage={currentPage}
          totalPages={data?.totalPages}
          paginate={paginate}
        />
      ) : (
        <ProjectCardView
          data={projectList}
          currentPage={currentPage}
          totalPages={data?.totalPages}
          paginate={paginate}
        />
      )}

      {manageProject?.isOpen && (
        <GlobalModel
          size="md"
          isOpen={manageProject?.isOpen}
          closeModal={() => setMangeProject({ isOpen: false, Project: null })}
        >
          <ManageProjectInfo
            project={manageProject?.Project}
            onClose={() => setMangeProject({ isOpen: false, Project: null })}
          />
        </GlobalModel>
      )}
    </div>
  );
};

export default ProjectsDisplay;
