
import React, { useState, useEffect } from "react";
import "../../components/Project/ProjectInfra.css";
import BuildingModel from "../Project/Infrastructure/BuildingModel";
import FloorModel from "../Project/Infrastructure/FloorModel";
import showToast from "../../services/toastService";
import WorkAreaModel from "../Project/Infrastructure/WorkAreaModel";
import TaskModel from "../Project/Infrastructure/TaskModel";
import ProjectRepository from "../../repositories/ProjectRepository";
import Breadcrumb from "../../components/common/Breadcrumb";
import {useProjectDetails, useProjectInfra, useProjects} from "../../hooks/useProjects";
import {useHasUserPermission} from "../../hooks/useHasUserPermission";
import {APPROVE_TASK, ASSIGN_REPORT_TASK, MANAGE_PROJECT_INFRA} from "../../utils/constants";
import {useDispatch, useSelector} from "react-redux";
import {useProfile} from "../../hooks/useProfile";
import {refreshData, setProjectId} from "../../slices/localVariablesSlice";
import InfraTable from "../Project/Infrastructure/InfraTable";
import { useSelectedProject } from "../../slices/apiDataManager";
import Loader from "../common/Loader";




const InfraPlanning = () => {
  const { profile: LoggedUser, refetch: fetchData } = useProfile();
  const dispatch = useDispatch();
  const selectedProject = useSelectedProject();

  const { projectInfra, isLoading, isError, error, isFetched } = useProjectInfra(selectedProject);

  const canManageInfra = useHasUserPermission(MANAGE_PROJECT_INFRA);
  const canApproveTask = useHasUserPermission(APPROVE_TASK);
  const canReportTask = useHasUserPermission(ASSIGN_REPORT_TASK);

  const reloadedData = useSelector((store) => store.localVariables.reload);

  const hasAccess = canManageInfra || canApproveTask || canReportTask;

  if (isError) {
    return <div>{error?.response?.data?.message || error?.message}</div>;
  }

  if (!hasAccess && !isLoading) {
    return (
      <div className="text-center">
        <i className="fa-solid fa-triangle-exclamation fs-5"></i>
        <p>Access Denied: You don't have permission to perform this action.</p>
      </div>
    );
  }

  if (isLoading) {
    return <Loader />;
  }

  if (isFetched && (!projectInfra || projectInfra.length === 0)) {
    return (
      <div className="text-center">
        <p className="my-3">No Result Found</p>
      </div>
    );
  }

  return (
    <div className="col-md-12 col-lg-12 col-xl-12 order-0 mb-4">
        <div className="card-body" style={{ padding: "0.5rem" }}>
          <div className="row">
            <InfraTable buildings={projectInfra} projectId={selectedProject} />
        </div>
      </div>
    </div>
  );
};

export default InfraPlanning;

