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, useDesignation, useOrganization, } from "../../hooks/useDirectory"; import { useProjects } from "../../hooks/useProjects"; import SelectMultiple from "../common/SelectMultiple"; import { ContactSchema } from "./DirectorySchema"; import InputSuggestions from "../common/InputSuggestion"; const ManageDirectory = ({ submitContact, 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 { organizationList, loading: orgLoading } = useOrganization(); const { designationList, loading: designloading } = useDesignation(); const { contactTags, loading: Tagloading } = useContactTags(); const [IsSubmitting, setSubmitting] = useState(false); const [showSuggestions, setShowSuggestions] = useState(false); const [filteredDesignationList, setFilteredDesignationList] = useState([]); const dispatch = useDispatch(); const methods = useForm({ resolver: zodResolver(ContactSchema), defaultValues: { name: "", organization: "", contactCategoryId: null, address: "", description: "", designation: "", 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" }); useEffect(() => { if (emailFields.length === 0) { appendEmail({ label: "Work", emailAddress: "" }); } if (phoneFields.length === 0) { appendPhone({ label: "Office", phoneNumber: "" }); } }, [emailFields.length, phoneFields.length]); 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"); // handle logic when input of desgination is changed const handleDesignationChange = (e) => { const val = e.target.value; const matches = designationList.filter((org) => org.toLowerCase().includes(val.toLowerCase()) ); setFilteredDesignationList(matches); setShowSuggestions(true); setTimeout(() => setShowSuggestions(false), 5000); }; // handle logic when designation is selected const handleSelectDesignation = (val) => { setShowSuggestions(false); setValue("designation", val); }; 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 = (data) => { const cleaned = { ...data, contactEmails: (data.contactEmails || []).filter( (e) => e.emailAddress?.trim() !== "" ), contactPhones: (data.contactPhones || []).filter( (p) => p.phoneNumber?.trim() !== "" ), }; setSubmitting(true); submitContact(cleaned, reset, setSubmitting); }; const orgValue = watch("organization"); const handleClosed = () => { onCLosed(); }; return (
Create New Contact
{errors.name && ( {errors.name.message} )}
setValue("organization", val)} error={errors.organization?.message} />
{showSuggestions && filteredDesignationList.length > 0 && (
    {filteredDesignationList.map((designation) => (
  • handleSelectDesignation(designation)} onMouseEnter={(e) => (e.currentTarget.style.backgroundColor = "#f8f9fa") } onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = "transparent") } > {designation}
  • ))}
)} {errors.designation && ( {errors.designation.message} )}
{emailFields.map((field, index) => (
{errors.contactEmails?.[index]?.label && ( {errors.contactEmails[index].label.message} )}
{index === emailFields.length - 1 ? ( ) : ( removeEmail(index)} /> )}
{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 ? ( ) : ( removePhone(index)} /> )}
{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} )}