import React, { useEffect, useState } from "react"; import { useForm } from "react-hook-form"; import { z } from "zod"; import { zodResolver } from "@hookform/resolvers/zod"; import { MasterRespository } from "../../repositories/MastersRepository"; import { clearApiCacheKey } from "../../slices/apiCacheSlice"; import { getCachedData, cacheData } from "../../slices/apiDataManager"; import showToast from "../../services/toastService"; const schema = z.object({ name: z.string().min(1, { message: "Service Name is required" }), description: z .string() .min(1, { message: "Description is required" }) .max(255, { message: "Description cannot exceed 255 characters" }), serviceId: z.string().min(1, { message: "A service selection is required." }), }); const CreateActivityGroup = ({ onClose }) => { const [isLoading, setIsLoading] = useState(false); const [services, setServices] = useState(getCachedData("Services")); const { register, handleSubmit, formState: { errors }, reset, } = useForm({ resolver: zodResolver(schema), defaultValues: { name: "", description: "", serviceId: "", }, }); const handleServicesChange = (e) => { const { value } = e.target; const service = services.find((b) => b.id === String(value)); reset((prev) => ({ ...prev, serviceId: String(value), })); }; const onSubmit = (data) => { setIsLoading(true); const result = { name: data.name, description: data.description, serviceId: data.serviceId, }; MasterRespository.createActivityGroup(result) .then((resp) => { setIsLoading(false); resetForm(); const cachedData = getCachedData("Activity Group"); const updatedData = [...cachedData, resp?.data]; cacheData("Activity Group", updatedData); showToast("Activity Group Added successfully.", "success"); onClose(); }) .catch((error) => { showToast(error.message, "error"); setIsLoading(false); }); }; const resetForm = () => { reset({ name: "", description: "", serviceId: "", }); setDescriptionLength(0); }; useEffect(() => { if (!services) { MasterRespository.getServices().then((res) => { setServices(res?.data); cacheData("Services", res?.data); }); } return () => resetForm(); }, []); const [descriptionLength, setDescriptionLength] = useState(0); const maxDescriptionLength = 255; return ( <>
{/*
*/}
{errors.name &&

{errors.name.message}

}
{errors.serviceId && (

{errors.serviceId.message}

)}
{maxDescriptionLength - descriptionLength} characters left
{errors.description && (

{errors.description.message}

)}
); }; export default CreateActivityGroup;