import React, { useEffect, useState } from "react"; import { useForm,Controller } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import {z} from 'zod'; const currentDate = new Date().toISOString().split('T')[0]; const formatDate = (date) => { if (!date) { return currentDate; } const d = new Date(date); if (isNaN(d.getTime())) { return currentDate; } return d.toISOString().split('T')[0]; }; const ManageProjectInfo = ( {project,handleSubmitForm, onClose} ) => { const [CurrentProject,setCurrentProject] = useState() const [ isloading, setLoading ] = useState( false ) const projectSchema = z.object( { ...(project?.id ? { id: z.number().optional() } : {}), name: z.string().min( 1, {message: "Project Name is required"} ), contactPerson: z.string().min( 1, {message: "Contact Person Name is required"} ), projectAddress: z.string().min( 1, {message: "Address is required"} ).max(500, 'Address must not exceed 150 characters'), startDate: z.string().min( 1, {message: "Start Date is required"} ).default(currentDate), endDate: z.string().min( 1, {message: "End Date is required"} ).default(currentDate), projectStatusId: z .string() .min(1, { message: "Status is required" }) .transform((val) => { const num = Number(val); if (isNaN(num)) { throw new Error("Status must be a valid number"); } return num; }), } ) .refine((data) => { const start = new Date(data.startDate); const end = new Date(data.endDate); return end > start; }, { path: ['endDate'], // attaches the error to the endDate field message: 'End Date must be greater than Start Date', }); const {register, control, handleSubmit, formState: {errors}, reset, getValues} = useForm( { resolver: zodResolver( projectSchema ), defaultValues: { id:project?.id || "", name:project?.name || "", contactPerson:project?.contactPerson || "", projectAddress:project?.projectAddress || "", startDate: formatDate(project?.startDate )|| currentDate, endDate: formatDate(project?.endDate ) || currentDate, projectStatusId: String(project?.projectStatusId || "0"), } }) useEffect( () => { setCurrentProject(project) reset( project ? { id:project?.id || "", name:project?.name || "", contactPerson: project?.contactPerson || "", projectAddress: project?.projectAddress || "", startDate:formatDate(project?.startDate )|| "", endDate: formatDate(project?.endDate ) || "", projectStatusId: String(project.projectStatusId) || "0" , } :{} ) },[project,reset,]) const onSubmitForm = (updatedProject) => { setLoading( true ) handleSubmitForm( updatedProject ) }; useEffect( () => { return ()=>setLoading(false) },[]) return (
{project?.id ? "Edit Project" : "Create Project"}
{errors.name &&
{errors.name.message}
}
{errors.contactPerson &&
{errors.contactPerson.message}
}
{errors.startDate &&
{errors.startDate.message}
}
{errors.endDate &&
{errors.endDate.message}
}
{errors.projectStatusId &&
{errors.projectStatusId.message}
}