import React, { useEffect, useMemo } from "react"; import { useForm } from "react-hook-form"; import { z } from "zod"; import { zodResolver } from "@hookform/resolvers/zod"; import { useSelector } from "react-redux"; import { getCachedData } from "../../../slices/apiDataManager"; import showToast from "../../../services/toastService"; import { useManageProjectInfra } from "../../../hooks/useProjects"; import useSelect from "../../common/useSelect"; import Label from "../../common/Label"; const buildingSchema = z.object({ Id: z.string().optional(), name: z.string().min(1, "Building name is required"), description: z .string() .min(1, "Description is required") .max(160, "Description cannot exceed 160 characters"), }); const BuildingModel = ({ project, onClose, editingBuilding = null }) => { const selectedProject = useSelector( (store) => store.localVariables.projectId ); const { register, handleSubmit, formState: { errors }, setValue, watch, reset, } = useForm({ resolver: zodResolver(buildingSchema), defaultValues: { Id: "0", name: "", description: "", }, }); const watchedId = watch("Id"); const { mutate: ManageBuilding, isPending } = useManageProjectInfra({ onSuccessCallback: (data, variables) => { showToast( watchedId != "0" ? "Building updated Successfully" : "Building created Successfully", "success" ); reset({ Id: "0", name: "", description: "" }); // onClose?.(); }, }); const sortedBuildings = useMemo(() => { return (project || []) .filter((b) => b?.buildingName) .sort((a, b) => a.buildingName.localeCompare(b?.buildingName)); }, [project]); useEffect(() => { if (!watchedId || watchedId === "0") { setValue("name", ""); setValue("description", ""); } else { const selected = sortedBuildings.find((b) => String(b.id) === watchedId); if (selected) { setValue("name", selected.buildingName || ""); setValue("description", selected.description || ""); } } }, [watchedId, sortedBuildings, setValue]); useEffect(() => { if (editingBuilding) { reset({ Id: String(editingBuilding.id), name: editingBuilding.name, description: editingBuilding.description, }); } }, [editingBuilding]); const onSubmitHandler = (data) => { const payload = { ...data, Id: data.Id === "0" ? null : data.Id, projectId: selectedProject, }; let infraObject = [ { building: payload, floor: null, workArea: null, }, ]; ManageBuilding({ infraObject, projectId: selectedProject }); }; return (
Manage Buildings
{errors.Id && {errors.Id.message}}
{/* Name */}
{errors.name && ( {errors.name.message} )}
{/* Description */}