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 } from "../../hooks/useProjects";
import { useDispatch } from "react-redux";
import showToast from "../../services/toastService";
import { getCachedData, cacheData } from "../../slices/apiDataManager";
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";

const ProjectList = () => {
  const { profile: loginUser } = useProfile();
  const [listView, setListView] = useState(false);
  const [showModal, setShowModal] = useState(false);
  const { projects, loading, error, refetch } = useProjects();
  const [projectList, setProjectList] = useState([]);
  const HasManageProjectPermission = useHasUserPermission(MANAGE_PROJECT);
  const [HasManageProject, setHasManageProject] = useState(
    HasManageProjectPermission
  );
  const dispatch = useDispatch();

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

  const handleShow = () => setShowModal(true);
  const handleClose = () => setShowModal(false);

  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(sortedGrouped);
    }
  };

  useEffect(() => {
    sortingProject(projects);
  }, [projects, loginUser?.projects, loading]);

  useEffect(() => {
    if (loginUser) {
      setHasManageProject(HasManageProjectPermission);
    } else {
      setHasManageProject(false);
    }
  }, [loginUser, HasManageProjectPermission]);

  const handleSubmitForm = (newProject, setloading, reset) => {
    ProjectRepository.manageProject(newProject)
      .then((response) => {
        const cachedProjects = getCachedData("projectslist") || [];
        const updatedProjects = [...cachedProjects, response.data];
        cacheData("projectslist", updatedProjects);
        setProjectList((prev) => [...prev, response.data]);
        setloading(false);
        reset();
        sortingProject(getCachedData("projectslist"));
        showToast("Project Created successfully.", "success");
        setShowModal(false);
      })
      .catch((error) => {
        showToast(error.message, "error");
        setShowModal(false);
      });
  };

  const handleReFresh = () => {
    if (!projects || projects.length === 0) {
      refetch();
    }
  };

  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 indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = filteredProjects.slice(
    indexOfFirstItem,
    indexOfLastItem
  );
  const totalPages = Math.ceil(filteredProjects.length / itemsPerPage);
  console.log("filtter", currentItems);
  useEffect(() => {
    const tooltipTriggerList = Array.from(
      document.querySelectorAll('[data-bs-toggle="tooltip"]')
    );
    tooltipTriggerList.forEach((el) => new bootstrap.Tooltip(el));
  }, []);

  const handler = useCallback(
    async (msg) => {
      if (HasManageProject && msg.keyword === "Create_Project") {
        const updatedProjects = [...projectList, msg.response];
        cacheData("projectslist", updatedProjects);
        setProjectList(updatedProjects);
        sortingProject(updatedProjects);
      }

      if (
        msg.keyword === "Update_Project" &&
        projectList.some((item) => item.id === msg.response.id)
      ) {
        await refetch();
        sortingProject(projects);
      }
    },
    [HasManageProject, projects, sortingProject]
  );

  useEffect(() => {
    eventBus.on("project", handler);
    return () => eventBus.off("project", handler);
  }, [handler]);

  return (
    <>
      <div
        className={`modal fade ${showModal ? "show" : ""}`}
        tabIndex="-1"
        role="dialog"
        style={{ display: showModal ? "block" : "none" }}
        aria-hidden={!showModal}
      >
        <ManageProjectInfo
          project={null}
          handleSubmitForm={handleSubmitForm}
          onClose={handleClose}
        />
      </div>

      <div className="container-xxl flex-grow-1 container-p-y">
        <Breadcrumb
          data={[
            { label: "Home", link: "/dashboard" },
            { label: "Projects", link: null },
          ]}
        />

        <div className="d-flex flex-wrap justify-content-between align-items-start mb-4">
          <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 ${
                  !listView ? "btn-primary" : "btn-outline-primary"
                }`}
                onClick={() => setListView(false)}
                data-bs-toggle="tooltip"
                data-bs-offset="0,8"
                data-bs-placement="top"
                data-bs-custom-class="tooltip"
                title="Card View"
              >
                <i className="bx bx-grid-alt bx-sm"></i>
              </button>
              <button
                type="button"
                className={`btn btn-sm ${
                  listView ? "btn-primary" : "btn-outline-primary"
                }`}
                onClick={() => setListView(true)}
                data-bs-toggle="tooltip"
                data-bs-offset="0,8"
                data-bs-placement="top"
                data-bs-custom-class="tooltip"
                title="List View"
              >
                <i className="bx bx-list-ul bx-sm"></i>
              </button>
            </div>

            <div className="dropdown ms-3">
              <a
                className="dropdown-toggle hide-arrow cursor-pointer"
                data-bs-toggle="dropdown"
                aria-expanded="false"
              >
                <i className="bx bx-filter bx-lg"></i>
              </a>
              <ul className="dropdown-menu p-2 text-capitalize">
                {[
                  {
                    id: "b74da4c2-d07e-46f2-9919-e75e49b12731",
                    label: "Active",
                  },
                  {
                    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"
              className={`btn btn-sm btn-primary ${
                !HasManageProject && "d-none"
              }`}
              onClick={handleShow}
            >
              <i className="bx bx-plus-circle me-2"></i>
              Create New Project
            </button>
          </div>
        </div>

        {loading && <p className="text-center">Loading...</p>}
        {!loading && filteredProjects.length === 0 && !listView && (
          <p className="text-center text-muted">No projects found.</p>
        )}

        <div className="row">
          {listView ? (
            <div className="table-responsive text-nowrap py-2 ">
              <table className="table px-2">
                <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: "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>
                      <td colSpan="12" className="text-center py-4">
                        No projects found
                      </td>
                    </tr>
                  ) : (
                    currentItems.map((project) => (
                      <ProjectListView
                        key={project.id}
                        projectData={project}
                        recall={sortingProject}
                      />
                    ))
                  )}
                </tbody>
              </table>
            </div>
          ) : (
            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;
