import { useEffect, useState } from "react";
import Building from "./Building";
import Floor from "./Floor";
import FloorModel from "./FloorModel";
import showToast from "../../../services/toastService";
import ProjectRepository from "../../../repositories/ProjectRepository";

const InfraTable = ({ buildings }) => {
  const [projectBuilding, setProjectBuilding] = useState([]);
  const [expandedBuildings, setExpandedBuildings] = useState([]);
  const [showFloorModal, setShowFloorModal] = useState(false);
  const [selectedBuilding, setSelectedBuilding] = useState(null);
  const [clearTrigger, setClearTrigger] = useState(false);

  const toggleBuilding = (buildingId) => {
    setExpandedBuildings((prevExpanded) =>
      prevExpanded.includes(buildingId)
        ? prevExpanded.filter((id) => id !== buildingId)
        : [...prevExpanded, buildingId]
    );
  };

  const handleAddFloor = (building) => {
    setSelectedBuilding(building);
    setShowFloorModal(true);
  };

  const handleFloorSubmit = async (data) => {
    try {
      const payload = [
        {
          building: null,
          floor: {
            id: data.id || "0",
            floorName: data.floorName,
            buildingId: data.buildingId,
          },
          workArea: null,
        },
      ];

      const res = await ProjectRepository.manageProjectInfra(payload);

      if (res?.success) {
        showToast("Floor saved successfully!", "success");

        // Find and update the correct building
        const updatedBuildings = projectBuilding.map((b) => {
          if (b.id === parseInt(data.buildingId)) {
            const newFloor = {
              id: res.data?.[0]?.floor?.id || Math.random(),
              floorName: res.data?.[0]?.floor?.floorName || data.floorName,
              workAreas: [],
            };

            return {
              ...b,
              floors: [...(b.floors || []), newFloor],
            };
          }
          return b;
        });

        setProjectBuilding(updatedBuildings);
        setShowFloorModal(false);
        setClearTrigger(true);
      } else {
        showToast("Failed to save floor", "error");
      }
    } catch (err) {
   
      showToast("Error occurred while saving floor", "error");
    }
  };

  const handleClearComplete = () => {
    setClearTrigger(false);
  };

  const getContent = (building) => {
    return building.floors?.length > 0 ? (
      building.floors.map((floor) => (
        <Floor
          key={floor.id}
          forBuilding={building}
          floor={floor}
          workAreas={floor.workAreas}
        />
      ))
    ) : (
      <tr>
        <td colSpan="4">
          <div className=" mb-0" role="alert">
            <p className="fw-semibold">
              No floors have been added yet. Start by adding floors to manage
              this building.
            </p>
            <button
              type="button"
              className="btn btn-xs btn-primary"
              onClick={() => handleAddFloor(building)}
            >
              <i className="bx bx-plus-circle me-2"></i>
              Add Floors
            </button>
          </div>
        </td>
      </tr>
    );
  };
  useEffect(() => {
    setProjectBuilding(buildings);
  }, [buildings]);

  return (
    <div>
      {projectBuilding && projectBuilding.length > 0 && (
        <table className="table table-bordered">
          <tbody>
            {projectBuilding.map((building) => (
              <Building
                key={building.id}
                building={building}
                toggleBuilding={toggleBuilding}
                expandedBuildings={expandedBuildings}
                getContent={getContent}
              />
            ))}
          </tbody>
        </table>
      )}
      {showFloorModal && selectedBuilding && (
        <div
          className="modal fade show"
          id="floor-model"
          tabIndex="-1"
          style={{ display: "block" }}
          aria-modal="true"
          role="dialog"
        >
          <FloorModel
            project={{
              buildings: [selectedBuilding],
            }}
            onClose={() => setShowFloorModal(false)}
            onSubmit={handleFloorSubmit}
            onClearComplete={handleClearComplete}
          />
        </div>
      )}
    </div>
  );
};

export default InfraTable;
