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) { console.error("Error adding floor", err); showToast("Error occurred while saving floor", "error"); } }; const handleClearComplete = () => { setClearTrigger(false); }; const getContent = (building) => { return building.floors?.length > 0 ? ( building.floors.map((floor) => ( )) ) : (

No floors have been added yet. Please add floors to start managing your building.

); }; useEffect(() => { setProjectBuilding(buildings); }, [buildings]); return (
{projectBuilding && projectBuilding.length > 0 && ( {projectBuilding.map((building) => ( ))}
)} {showFloorModal && selectedBuilding && ( )}
); }; export default InfraTable;