import React, { useEffect, useState } from "react"; import { useForm, useFieldArray, FormProvider, useFormContext, } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import TagInput from "../common/TagInput"; import IconButton from "../common/IconButton"; import useMaster, { useContactCategory, useContactTags, } from "../../hooks/masterHook/useMaster"; import { useDispatch, useSelector } from "react-redux"; import { changeMaster } from "../../slices/localVariablesSlice"; import { useBuckets, useOrganization } from "../../hooks/useDirectory"; import { useProjects } from "../../hooks/useProjects"; import SelectMultiple from "../common/SelectMultiple"; import { ContactSchema } from "./DirectorySchema"; import InputSuggestions from "../common/InputSuggestion"; const UpdateContact = ({ submitContact, existingContact, onCLosed }) => { const selectedMaster = useSelector( (store) => store.localVariables.selectedMaster ); const [categoryData, setCategoryData] = useState([]); const [TagsData, setTagsData] = useState([]); const { data, loading } = useMaster(); const { buckets, loading: bucketsLoaging } = useBuckets(); const { projects, loading: projectLoading } = useProjects(); const { contactCategory, loading: contactCategoryLoading } = useContactCategory(); const { contactTags, loading: Tagloading } = useContactTags(); const [ IsSubmitting, setSubmitting ] = useState( false ); const [isInitialized, setIsInitialized] = useState(false); const dispatch = useDispatch(); const {organizationList} = useOrganization() const methods = useForm({ resolver: zodResolver(ContactSchema), defaultValues: { name: "", organization: "", contactCategoryId: null, address: "", description: "", projectIds: [], contactEmails: [], contactPhones: [], tags: [], bucketIds: [], }, }); const { register, handleSubmit, control, getValues, trigger, setValue, watch, reset, formState: { errors }, } = methods; const { fields: emailFields, append: appendEmail, remove: removeEmail, } = useFieldArray({ control, name: "contactEmails" }); const { fields: phoneFields, append: appendPhone, remove: removePhone, } = useFieldArray({ control, name: "contactPhones" }); const handleAddEmail = async () => { const emails = getValues("contactEmails"); const lastIndex = emails.length - 1; const valid = await trigger(`contactEmails.${lastIndex}.emailAddress`); if (valid) { appendEmail({ label: "Work", emailAddress: "" }); } }; const handleAddPhone = async () => { const phones = getValues("contactPhones"); const lastIndex = phones.length - 1; const valid = await trigger(`contactPhones.${lastIndex}.phoneNumber`); if (valid) { appendPhone({ label: "Office", phoneNumber: "" }); } }; const watchBucketIds = watch("bucketIds"); const toggleBucketId = (id) => { const updated = watchBucketIds?.includes(id) ? watchBucketIds.filter((val) => val !== id) : [...watchBucketIds, id]; setValue("bucketIds", updated, { shouldValidate: true }); }; const handleCheckboxChange = (id) => { const updated = watchBucketIds.includes(id) ? watchBucketIds.filter((i) => i !== id) : [...watchBucketIds, id]; setValue("bucketIds", updated, { shouldValidate: true }); }; const onSubmit = async (data) => { const cleaned = { ...data, contactEmails: (data.contactEmails || []) .filter((e) => e.emailAddress?.trim() !== "") .map((email, index) => { const existingEmail = existingContact.contactEmails?.[index]; return existingEmail ? { ...email, id: existingEmail.id } : email; }), contactPhones: (data.contactPhones || []) .filter((p) => p.phoneNumber?.trim() !== "") .map((phone, index) => { const existingPhone = existingContact.contactPhones?.[index]; return existingPhone ? { ...phone, id: existingPhone.id } : phone; }), }; setSubmitting(true); await submitContact({ ...cleaned, id: existingContact.id }); setSubmitting(false); }; const orgValue = watch("organization") const handleClosed = () => { onCLosed(); }; useEffect(() => { const isValidContact = existingContact && typeof existingContact === "object" && !Array.isArray(existingContact); if (!isInitialized &&isValidContact && TagsData) { reset({ name: existingContact.name || "", organization: existingContact.organization || "", contactEmails: existingContact.contactEmails || [], contactPhones: existingContact.contactPhones || [], contactCategoryId: existingContact.contactCategory?.id || null, address: existingContact.address || "", description: existingContact.description || "", projectIds: existingContact.projectIds || null, tags: existingContact.tags || [], bucketIds: existingContact.bucketIds || [], } ); if (!existingContact.contactPhones || existingContact.contactPhones.length === 0) { appendPhone({ label: "Office", phoneNumber: "" }); } if (!existingContact.contactEmails || existingContact.contactEmails.length === 0) { appendEmail({ label: "Work", emailAddress: "" }); } setIsInitialized(true) } // return()=> reset() }, [ existingContact, buckets, projects ] ); return (
Update Contact
{errors.name && ( {errors.name.message} )}
setValue("organization", val)} error={errors.organization?.message} /> {errors.organization && ( {errors.organization.message} )}
{emailFields.map((field, index) => (
{errors.contactEmails?.[index]?.label && ( {errors.contactEmails[index].label.message} )}
{index === emailFields.length - 1 ? ( //
{errors.contactEmails?.[index]?.emailAddress && ( {errors.contactEmails[index].emailAddress.message} )}
))}
{phoneFields.map((field, index) => (
{errors.phone?.[index]?.label && ( {errors.ContactPhones[index].label.message} )}
{index === phoneFields.length - 1 ? ( //
{errors.contactPhones?.[index]?.phoneNumber && ( {errors.contactPhones[index].phoneNumber.message} )}
))}
{errors.contactPhone?.message && (
{errors.contactPhone.message}
)}
{errors.contactCategoryId && ( {errors.contactCategoryId.message} )}
{errors.projectIds && ( {errors.projectIds.message} )}
{errors.tags && ( {errors.tags.message} )}
    {bucketsLoaging &&

    Loading...

    } {buckets?.map((item) => (
  • handleCheckboxChange(item.id)} />
  • ))} {errors.bucketIds && ( {errors.bucketIds.message} )}