import React, { useState, useEffect, useCallback } from "react";
import ProjectCard from "../../components/Project/ProjectCard";
import ManageProjectInfo from "../../components/Project/ManageProjectInfo";
import Breadcrumb from "../../components/common/Breadcrumb";
import ProjectRepository from "../../repositories/ProjectRepository";
import { useProjects, useCreateProject } from "../../hooks/useProjects";
import showToast from "../../services/toastService";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { useProfile } from "../../hooks/useProfile";
import { ITEMS_PER_PAGE, MANAGE_PROJECT } from "../../utils/constants";
import ProjectListView from "./ProjectListView";
import eventBus from "../../services/eventBus";
import { clearApiCacheKey } from "../../slices/apiCacheSlice";
import { defaultCheckBoxAppearanceProvider } from "pdf-lib";
import { useMutation } from "@tanstack/react-query";
import usePagination from "../../hooks/usePagination";
import GlobalModel from "../../components/common/GlobalModel";
import { useDispatch, useSelector } from "react-redux";
import { setProjectId } from "../../slices/localVariablesSlice";

const ProjectList = () => {
  const { profile: loginUser } = useProfile();
  const [listView, setListView] = useState(false);
  const [showModal, setShowModal] = useState(false);
  const selectedProject = useSelector(
    (store) => store.localVariables.projectId
  );
  const dispatch = useDispatch();

  const { projects, loading, error, refetch } = useProjects();
  const [projectList, setProjectList] = useState([]);

  const HasManageProjectPermission = useHasUserPermission(MANAGE_PROJECT);
  const [HasManageProject, setHasManageProject] = useState(
    HasManageProjectPermission
  );

  const { mutate: createProject, isPending } = useCreateProject({
    onSuccessCallback: () => {
      setShowModal(false);
    },
  });

  const [searchTerm, setSearchTerm] = useState("");
  const [selectedStatuses, setSelectedStatuses] = useState([
    "b74da4c2-d07e-46f2-9919-e75e49b12731",
    "603e994b-a27f-4e5d-a251-f3d69b0498ba",
    "ef1c356e-0fe0-42df-a5d3-8daee355492d",
    "cdad86aa-8a56-4ff4-b633-9c629057dfef",
    "33deaef9-9af1-4f2a-b443-681ea0d04f81",
  ]);

  const handleShow = () => setShowModal(true);
  const handleClose = () => setShowModal(false);
  useEffect(() => {
    dispatch(setProjectId(null));
  }, []);
  const sortingProject = (projects) => {
    if (!loading && Array.isArray(projects)) {
      const grouped = {};
      projects.forEach((project) => {
        const statusId = project.projectStatusId;
        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 (!loading && projects) {
      sortingProject(projects);
    }
  }, [projects, loading, selectedStatuses]);

  useEffect(() => {
    setHasManageProject(loginUser ? HasManageProjectPermission : false);
  }, [loginUser, HasManageProjectPermission]);

  const handleSubmitForm = (newProject) => {
    createProject(newProject);
  };

  const handleStatusChange = (statusId) => {
    setCurrentPage(1);
    setSelectedStatuses((prev) =>
      prev.includes(statusId)
        ? prev.filter((id) => id !== statusId)
        : [...prev, statusId]
    );
  };

  const handleStatusFilterFromChild = (statusesFromChild) => {
    setSelectedStatuses(statusesFromChild);
  };

  const filteredProjects = projectList.filter((project) => {
    const matchesStatus = selectedStatuses.includes(project.projectStatusId);
    const matchesSearch = project.name
      .toLowerCase()
      .includes(searchTerm.toLowerCase());
    return matchesStatus && matchesSearch;
  });

  const totalPages = Math.ceil(filteredProjects.length / ITEMS_PER_PAGE);

  const { currentItems, currentPage, paginate, setCurrentPage } = usePagination(
    filteredProjects,
    ITEMS_PER_PAGE
  );

  useEffect(() => {
    const tooltipTriggerList = Array.from(
      document.querySelectorAll('[data-bs-toggle="tooltip"]')
    );
    tooltipTriggerList.forEach((el) => new bootstrap.Tooltip(el));
  }, []);

  return (
    <>
      {showModal && (
        <GlobalModel isOpen={showModal} closeModal={handleClose}>
          <ManageProjectInfo
            project={null}
            handleSubmitForm={handleSubmitForm}
            onClose={handleClose}
            isPending={isPending}
          />
        </GlobalModel>
      )}

      <div className="container-fluid">
        <Breadcrumb
          data={[
            { label: "Home", link: "/dashboard" },
            { label: "Projects", link: null },
          ]}
        />
        <div className="card cursor-pointer mb-5">
          <div className="card-body p-2 pb-1">
            <div className="d-flex flex-wrap justify-content-between align-items-start">
              <div className="d-flex flex-wrap align-items-start">
                <div className="flex-grow-1 me-2 mb-2">
                  <input
                    type="search"
                    className="form-control form-control-sm"
                    placeholder="Search projects..."
                    value={searchTerm}
                    onChange={(e) => {
                      setSearchTerm(e.target.value);
                      setCurrentPage(1);
                    }}
                  />
                </div>

                <div className="d-flex gap-2 mb-2">
                  <button
                    type="button"
                    className={`btn  btn-sm p-1 ${
                      !listView ? "btn-primary" : "btn-outline-primary"
                    }`}
                    onClick={() => setListView(false)}
                    data-bs-toggle="tooltip"
                    data-bs-custom-class="tooltip"
                    title="Card View"
                  >
                    <i className="bx bx-grid-alt fs-5"></i>
                  </button>
                  <button
                    type="button"
                    className={`btn btn-sm p-1  ${
                      listView ? "btn-primary" : "btn-outline-primary"
                    }`}
                    onClick={() => setListView(true)}
                    data-bs-toggle="tooltip"
                    data-bs-custom-class="tooltip"
                    title="List View"
                  >
                    <i className="bx bx-list-ul fs-5"></i>
                  </button>
                </div>

                 <div className="dropdown mt-1">
                  <a
                    className="dropdown-toggle hide-arrow cursor-pointer p-1 mt-3 "
                    data-bs-toggle="dropdown"
                    aria-expanded="false"
                    data-bs-custom-class="tooltip"
                    title="Filter"
                  >
                    <i className="bx bx-slider-alt ms-1"></i>
                  </a>
                  <ul className="dropdown-menu p-2 text-capitalize">
                    {[
                      {
                        id: "b74da4c2-d07e-46f2-9919-e75e49b12731",
                        label: "Active",
                      },
                      {
                        id: "cdad86aa-8a56-4ff4-b633-9c629057dfef",
                        label: "In Progress",
                      },
                      {
                        id: "603e994b-a27f-4e5d-a251-f3d69b0498ba",
                        label: "On Hold",
                      },
                      {
                        id: "ef1c356e-0fe0-42df-a5d3-8daee355492d",
                        label: "Inactive",
                      },
                      {
                        id: "33deaef9-9af1-4f2a-b443-681ea0d04f81",
                        label: "Completed",
                      },
                    ].map(({ id, label }) => (
                      <li key={id}>
                        <div className="form-check">
                          <input
                            className="form-check-input  "
                            type="checkbox"
                            checked={selectedStatuses.includes(id)}
                            onChange={() => handleStatusChange(id)}
                          />
                          <label className="form-check-label">{label}</label>
                        </div>
                      </li>
                    ))}
                  </ul>
                </div>
              </div>

              <div>
                <button
                  type="button"
                  data-bs-toggle="tooltip"
                  data-bs-offset="0,8"
                  data-bs-placement="top"
                  data-bs-custom-class="tooltip"
                  title="Add New Project"
                  className={`p-1 me-2 bg-primary rounded-circle ${
                    !HasManageProject && "d-none"
                  }`}
                  onClick={handleShow}
                >
                  <i className="bx bx-plus fs-4 text-white"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
        {loading && <p className="text-center">Loading...</p>}
        {!loading && filteredProjects.length === 0 && !listView && (
          <p className="text-center text-muted">No projects found.</p>
        )}

        {listView ? (
          <div className="card cursor-pointer">
            <div className="card-body p-2">
              <div
                className="table-responsive text-nowrap py-2 mx-2"
                style={{ minHeight: "200px" }}
              >
                <table className="table m-0">
                  <thead>
                    <tr>
                      <th className="text-start" colSpan={5}>
                        Project Name
                      </th>
                      <th className="mx-2 text-start">Contact Person</th>
                      <th className="mx-2">START DATE</th>
                      <th className="mx-2">DEADLINE</th>
                      <th className="mx-2">Task</th>
                      <th className="mx-2">Progress</th>
                      <th className="mx-2">
                        <div className="dropdown">
                          <a
                            className="dropdown-toggle hide-arrow cursor-pointer"
                            data-bs-toggle="dropdown"
                            aria-expanded="false"
                          >
                            Status <i className="bx bx-filter bx-sm"></i>
                          </a>
                          <ul className="dropdown-menu p-2 text-capitalize">
                            {[
                              {
                                id: "b74da4c2-d07e-46f2-9919-e75e49b12731",
                                label: "Active",
                              },
                              {
                                id: "cdad86aa-8a56-4ff4-b633-9c629057dfef",
                                label: "In Progress",
                              },
                              {
                                id: "603e994b-a27f-4e5d-a251-f3d69b0498ba",
                                label: "On Hold",
                              },
                              {
                                id: "ef1c356e-0fe0-42df-a5d3-8daee355492d",
                                label: "Inactive",
                              },
                              {
                                id: "33deaef9-9af1-4f2a-b443-681ea0d04f81",
                                label: "Completed",
                              },
                            ].map(({ id, label }) => (
                              <li key={id}>
                                <div className="form-check">
                                  <input
                                    className="form-check-input  "
                                    type="checkbox"
                                    checked={selectedStatuses.includes(id)}
                                    onChange={() => handleStatusChange(id)}
                                  />
                                  <label className="form-check-label">
                                    {label}
                                  </label>
                                </div>
                              </li>
                            ))}
                          </ul>
                        </div>
                      </th>
                      <th
                        className={`mx-2 ${
                          HasManageProject ? "d-sm-table-cell" : "d-none"
                        }`}
                      >
                        Action
                      </th>
                    </tr>
                  </thead>
                  <tbody className="table-border-bottom-0 overflow-auto ">
                    {currentItems.length === 0 ? (
                      <tr className="text-center">
                        <td
                          colSpan="12"
                          rowSpan="12"
                          style={{ height: "200px" }}
                        >
                          No projects found
                        </td>
                      </tr>
                    ) : (
                      currentItems.map((project) => (
                        <ProjectListView
                          key={project.id}
                          projectData={project}
                          recall={sortingProject}
                        />
                      ))
                    )}
                  </tbody>
                </table>
              </div>{" "}
            </div>{" "}
          </div>
        ) : (
          <div className="row">
            {currentItems.map((project) => (
              <ProjectCard
                key={project.id}
                projectData={project}
                recall={sortingProject}
              />
            ))}
          </div>
        )}

        {!loading && totalPages > 1 && (
          <nav>
            <ul className="pagination pagination-sm justify-content-end py-2">
              <li className={`page-item ${currentPage === 1 && "disabled"}`}>
                <button
                  className="page-link"
                  onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                >
                  &laquo;
                </button>
              </li>
              {[...Array(totalPages)].map((_, i) => (
                <li
                  key={i}
                  className={`page-item ${currentPage === i + 1 && "active"}`}
                >
                  <button
                    className="page-link"
                    onClick={() => setCurrentPage(i + 1)}
                  >
                    {i + 1}
                  </button>
                </li>
              ))}
              <li
                className={`page-item ${
                  currentPage === totalPages && "disabled"
                }`}
              >
                <button
                  className="page-link"
                  onClick={() =>
                    setCurrentPage((p) => Math.min(totalPages, p + 1))
                  }
                >
                  &raquo;
                </button>
              </li>
            </ul>
          </nav>
        )}
      </div>
    </>
  );
};

export default ProjectList;
