import React, { useState, useEffect, useCallback } from "react";
import "./ProjectInfra.css";
import BuildingModel from "./Infrastructure/BuildingModel";
import FloorModel from "./Infrastructure/FloorModel";
import showToast from "../../services/toastService";
import WorkAreaModel from "./Infrastructure/WorkAreaModel";
import TaskModel from "./Infrastructure/TaskModel";
import ProjectRepository, {
  TasksRepository,
} from "../../repositories/ProjectRepository";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { MANAGE_PROJECT_INFRA, MANAGE_TASK } from "../../utils/constants";
import InfraTable from "./Infrastructure/InfraTable";
import {
  cacheData,
  clearCacheKey,
  getCachedData,
  useSelectedProject,
} from "../../slices/apiDataManager";
import {
  useCurrentService,
  useProjectAssignedServices,
  useProjectDetails,
  useProjectInfra,
} from "../../hooks/useProjects";
import { useDispatch, useSelector } from "react-redux";
import { refreshData } from "../../slices/localVariablesSlice";
import eventBus from "../../services/eventBus";
import { useParams } from "react-router-dom";
import GlobalModel from "../common/GlobalModel";
import { setService } from "../../slices/globalVariablesSlice";

const ProjectInfra = ({ data, onDataChange, eachSiteEngineer }) => {
  const projectId = useSelectedProject();
  const selectedService = useCurrentService();
  const reloadedData = useSelector((store) => store.localVariables.reload);
  const [expandedBuildings, setExpandedBuildings] = useState([]);
  const { projectInfra, isLoading, error } = useProjectInfra(projectId);
  const { projects_Details, refetch, loading } = useProjectDetails(data?.id);
  const [project, setProject] = useState(projects_Details);
  const ManageInfra = useHasUserPermission(MANAGE_PROJECT_INFRA);
  const ManageTask = useHasUserPermission(MANAGE_TASK);
  const [showModalFloor, setshowModalFloor] = useState(false);
  const [showModalWorkArea, setshowModalWorkArea] = useState(false);
  const [showModalTask, setshowModalTask] = useState(false);
  const [showModalBuilding, setshowModalBuilding] = useState(false);
  const dispatch = useDispatch();
  const { data: assignedServices, isLoading: servicesLoading } =
    useProjectAssignedServices(projectId);


  useEffect(() => {
    setProject(projectInfra);
  }, [data, projects_Details]);

  const signalRHandler = (response) => {
    setProject(response);
  };

  return (
    <>
      {showModalBuilding && (
        <GlobalModel
          isOpen={showModalBuilding}
          size="md"
          closeModal={() => setshowModalBuilding(false)}
        >
          <BuildingModel
            project={projectInfra}
            onClose={() => setshowModalBuilding(false)}
          />
        </GlobalModel>
      )}
      {showModalFloor && (
        <GlobalModel
          isOpen={showModalFloor}
          size="md"
          closeModal={() => setshowModalFloor(false)}
        >
          <FloorModel
            project={projectInfra}
            onClose={() => setshowModalFloor(false)}
          />
        </GlobalModel>
      )}
      {showModalWorkArea && (
        <GlobalModel
          isOpen={showModalWorkArea}
          size="lg"
          closeModal={() => setshowModalWorkArea(false)}
        >
          <WorkAreaModel
            project={projectInfra}
            onClose={() => setshowModalWorkArea(false)}
          />
        </GlobalModel>
      )}
      {showModalTask && (
        <GlobalModel
          isOpen={showModalTask}
          size="lg"
          closeModal={() => setshowModalTask(false)}
        >
          <TaskModel
            project={projectInfra}
            onClose={() => setshowModalTask(false)}
          />
        </GlobalModel>
      )}
      <div className="col-md-12 col-lg-12 col-xl-12 order-0 mb-4">
        <div className="card">
          <div className="card-body" style={{ padding: "0.5rem" }}>
            <div className="align-items-center">
              <div className="row ">
                <div
                  className="dataTables_length text-start py-2 px-6 col-md-4 col-12"
                  id="DataTables_Table_0_length"
                >
                  {!servicesLoading &&
                    assignedServices?.length > 0 &&
                    (assignedServices.length > 1 ? (
                      <label>
                        <select
                          name="DataTables_Table_0_length"
                          aria-controls="DataTables_Table_0"
                          className="form-select form-select-sm"
                          aria-label="Select Service"
                          value={selectedService}
                          onChange={(e) => dispatch(setService(e.target.value))}
                        >
                          <option value="">All Services</option>
                          {assignedServices.map((service) => (
                            <option key={service.id} value={service.id}>
                              {service.name}
                            </option>
                          ))}
                        </select>
                      </label>
                    ) : (
                      <h5>{assignedServices[0].name}</h5>
                    ))}
                </div>

                {/* Buttons Section (aligned to right) */}
                <div className="col-md-8 col-12 text-end mb-1">
                  {ManageInfra && (
                    <>
                      <button
                        type="button"
                        className="link-button btn btn-xs rounded-md link-button-sm m-1 btn-primary"
                        onClick={() => setshowModalBuilding(true)}
                      >
                        <i className="bx bx-plus-circle me-2"></i>
                        Manage Building
                      </button>
                      <button
                        type="button"
                        className="link-button btn btn-xs rounded-md m-1 btn-primary"
                        onClick={() => setshowModalFloor(true)}
                      >
                        <i className="bx bx-plus-circle me-2"></i>
                        Manage Floors
                      </button>
                      <button
                        type="button"
                        className="link-button btn btn-xs rounded-md m-1 btn-primary"
                        onClick={() => setshowModalWorkArea(true)}
                      >
                        <i className="bx bx-plus-circle me-2"></i>
                        Manage Work Areas
                      </button>
                    </>
                  )}

                  {(ManageTask || ManageInfra) && (
                    <button
                      type="button"
                      className="link-button btn btn-xs rounded-md m-1 btn-primary"
                      onClick={() => setshowModalTask(true)}
                    >
                      <i className="bx bx-plus-circle me-2"></i>
                      Create Tasks
                    </button>
                  )}
                </div>
              </div>
              <div className="row ">
                {isLoading && <p>Loading....</p>}
                {projectInfra && projectInfra?.length > 0 && (
                  <InfraTable
                    buildings={projectInfra}
                    projectId={projectId}
                    serviceId={selectedService}
                  />
                )}
                {!isLoading && projectInfra?.length == 0 && (
                  <div className="mt-5">
                    <p>No Infra Avaiable</p>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default ProjectInfra;
