import React, { useEffect, useState } from "react"; import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; import showToast from "../../../services/toastService"; import { useManageProjectInfra } from "../../../hooks/useProjects"; import { useSelector } from "react-redux"; const workAreaSchema = z.object({ id: z.string().optional(), buildingId: z.string().refine((val) => val !== "0", { message: "Building is required", }), floorId: z.string().refine((val)=>val !== "0",{message:"Floor is required"}), areaName: z.string().min(3, "Work Area Name must be at least 3 characters"), }); const defaultModel = { id: "0", buildingId: "0", floorId: "0", areaName: "", }; const WorkAreaModel = ({ project, onSubmit, onClose }) => { const [selectedBuilding, setSelectedBuilding] = useState(null); const [selectedFloor, setSelectedFloor] = useState(null); const selectedProject = useSelector((store)=>store.localVariables.projectId) const { register, handleSubmit, formState: { errors }, setValue, reset, watch, } = useForm({ resolver: zodResolver(workAreaSchema), defaultValues: defaultModel, }); const watchBuildingId = watch("buildingId"); const watchFloorId = watch("floorId"); const watchWorkAreaId = watch("id"); const { mutate: ManageWorkArea, isPending } = useManageProjectInfra({ onSuccessCallback: (data, variables) => { showToast( watchWorkAreaId != "0" ? "Wrok Area updated Successfully" : "Work Area created Successfully", "success" ); reset({ id: "0", buildingId: "0", areaName: "", floorId: "0" }); // onClose?.(); }, }); useEffect(() => { const building = project?.find((b) => b.id === watchBuildingId); setSelectedBuilding(building || null); if (building) { const floor = building.floors?.find((f) => f.id === watchFloorId); setSelectedFloor(floor || null); setValue("areaName", ""); } else { setSelectedFloor(null); setValue("floorId", "0"); setValue("areaName", ""); } }, [watchBuildingId, watchFloorId]); const handleWrokAreaChange = (e) => { const workAreaId = e.target.value; setValue("id", workAreaId); const area = selectedFloor?.workAreas.find((w) => w.id === workAreaId); if (area) { setValue("areaName", area.areaName); } else { setValue("areaName", ""); } }; useEffect(() => { reset(defaultModel); }, []); const onSubmitForm = ( data ) => { const payload = { id: data.id === "0" ? null : data.id, areaName: data.areaName, floorId: data.floorId, buildingId: data.buildingId, }; let infraObject = [ { building: null, floor: null, workArea: payload, }, ]; ManageWorkArea({ infraObject, projectId: selectedProject }); }; return (
); }; export default WorkAreaModel;