240 lines
7.2 KiB
TypeScript
240 lines
7.2 KiB
TypeScript
// ContactForm.tsx
|
|
import React, { useEffect, useState } from "react";
|
|
import { FaSpinner } from "react-icons/fa";
|
|
|
|
export interface ContactData {
|
|
contactId?: number;
|
|
email: string;
|
|
firstName: string;
|
|
lastName: string;
|
|
title: string;
|
|
company: string;
|
|
website: string;
|
|
phone: string;
|
|
}
|
|
|
|
interface Props {
|
|
onSubmit: (data: ContactData) => void;
|
|
loading: boolean;
|
|
setShowModal: () => React.Dispatch<React.SetStateAction<boolean>>;
|
|
actionStatus: string;
|
|
editJsonData: any;
|
|
}
|
|
|
|
const ContactFormModal = ({
|
|
onSubmit,
|
|
loading,
|
|
setShowModal,
|
|
actionStatus,
|
|
editJsonData,
|
|
}: Props) => {
|
|
const [formData, setFormData] = useState<ContactData>({
|
|
email: "",
|
|
firstName: "",
|
|
lastName: "",
|
|
title: "",
|
|
company: "",
|
|
website: "",
|
|
phone: "",
|
|
});
|
|
|
|
const [errors, setErrors] = useState<{ [key: string]: string }>({});
|
|
|
|
useEffect(() => {
|
|
if (actionStatus === "Edit" && editJsonData) {
|
|
setFormData({
|
|
email: editJsonData.email,
|
|
firstName: editJsonData.firstName,
|
|
lastName: editJsonData.lastName,
|
|
title: editJsonData.title,
|
|
company: editJsonData.company,
|
|
website: editJsonData.website,
|
|
phone: editJsonData.phone,
|
|
});
|
|
}
|
|
}, [actionStatus, editJsonData]);
|
|
|
|
const handleChange = (field: keyof ContactData, value: string) => {
|
|
setFormData((prev) => ({ ...prev, [field]: value }));
|
|
if (errors[field]) {
|
|
setErrors((prev) => ({ ...prev, [field]: "" }));
|
|
}
|
|
};
|
|
|
|
// const handlePhoneChange = (index: number, value: string) => {
|
|
// const numericValue = value.replace(/\D/g, ""); // Remove non-numeric
|
|
// const updatedPhones = [...formData.phone];
|
|
// updatedPhones[index] = numericValue;
|
|
// setFormData((prev) => ({ ...prev, phones: updatedPhones }));
|
|
|
|
// const errorKey = `phones_${index}`;
|
|
// if (errors[errorKey]) {
|
|
// setErrors((prev) => ({ ...prev, [errorKey]: "" }));
|
|
// }
|
|
// };
|
|
|
|
// const addPhoneField = () => {
|
|
// setFormData((prev) => ({ ...prev, phone: [...prev.phone, ''] }));
|
|
// };
|
|
|
|
// const removePhoneField = (index: number) => {
|
|
// const updatedPhones = formData.phones.filter((_, i) => i !== index);
|
|
// setFormData((prev) => ({ ...prev, phones: updatedPhones }));
|
|
// };
|
|
|
|
const validate = () => {
|
|
const newErrors: { [key: string]: string } = {};
|
|
|
|
const emailRegex = /\S+@\S+\.\S+/;
|
|
// const nameRegex = /^[a-zA-Z\s\-']+$/;
|
|
const urlRegex = /^(https?:\/\/)?([\w-]+\.)+[\w-]{2,}(\/.*)?$/;
|
|
const phoneRegex =
|
|
/^\+?\d{1,4}?[-.\s]?\(?\d{2,5}\)?[-.\s]?\d{3,5}[-.\s]?\d{3,5}$/;
|
|
|
|
// Email
|
|
if (!formData.email.trim()) {
|
|
newErrors.email = "Email is required";
|
|
} else if (!emailRegex.test(formData.email)) {
|
|
newErrors.email = "Invalid email address";
|
|
}
|
|
|
|
// // First Name
|
|
// if (!formData.firstName.trim()) {
|
|
// newErrors.firstName = 'First name is required';
|
|
// } else
|
|
// if (formData.firstName.trim() && !nameRegex.test(formData.firstName)) {
|
|
// newErrors.firstName = "First name contains invalid characters";
|
|
// }
|
|
|
|
// Last Name
|
|
if (!formData.lastName.trim()) {
|
|
newErrors.lastName = "Last name is required";
|
|
}
|
|
// else if (!nameRegex.test(formData.lastName)) {
|
|
// newErrors.lastName = "Last name contains invalid characters";
|
|
// }
|
|
|
|
// // Title
|
|
// if (!formData.title.trim()) {
|
|
// newErrors.title = 'Title is required';
|
|
// }
|
|
|
|
// Website (optional but validate if present)
|
|
if (formData.website.trim() && !urlRegex.test(formData.website)) {
|
|
newErrors.website = "Invalid website URL";
|
|
}
|
|
|
|
// Phone
|
|
if (formData.phone.trim() && !phoneRegex.test(formData.phone)) {
|
|
newErrors.phone = "Phone number must contain only digits";
|
|
}
|
|
return newErrors;
|
|
};
|
|
|
|
const handleSubmit = async () => {
|
|
const validationErrors = validate();
|
|
let type = "Add";
|
|
let payload = formData;
|
|
|
|
if (Object.keys(validationErrors).length > 0) {
|
|
setErrors(validationErrors);
|
|
return;
|
|
}
|
|
try {
|
|
if (actionStatus === "Edit") {
|
|
type = "Edit";
|
|
payload = {
|
|
...formData,
|
|
contactId: editJsonData.id,
|
|
};
|
|
}
|
|
await onSubmit(payload, type);
|
|
|
|
setFormData({
|
|
email: "",
|
|
firstName: "",
|
|
lastName: "",
|
|
title: "",
|
|
company: "",
|
|
website: "",
|
|
phone: "",
|
|
});
|
|
setErrors({});
|
|
} catch (err) {
|
|
console.error("Submit failed:", err);
|
|
}
|
|
};
|
|
|
|
|
|
|
|
return (
|
|
<div className="fixed inset-0 z-50 flex items-center justify-center backdrop-blur-sm bg-black/30 bg-opacity-50 p-4 sm:p-6">
|
|
<div className="bg-white rounded-md p-6 max-w-[700px] w-full sm:max-w-[700px] shadow-lg relative overflow-auto max-h-[90vh]">
|
|
<div className="space-y-4">
|
|
<h2 className="text-lg font-medium text-slate-500">{`${actionStatus} Contact`}</h2>
|
|
|
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
|
{[
|
|
{ label: "First Name", field: "firstName" },
|
|
{ label: "Last Name", field: "lastName" },
|
|
{ label: "Email", field: "email", fieldType: "email" },
|
|
{ label: "Title", field: "title" },
|
|
{ label: "Company", field: "company" },
|
|
{ label: "Website", field: "website", fieldType: "url" },
|
|
{ label: "Phone", field: "phone", fieldType: "tel" },
|
|
].map(({ label, field, fieldType }) => (
|
|
<div key={field} className="flex flex-col">
|
|
<label className="text-sm font-medium text-[var(--greyTextCol)] mb-1">
|
|
{label}
|
|
</label>
|
|
<input
|
|
type={fieldType ?? "text"}
|
|
value={(formData[field as keyof ContactData] as string) || ""}
|
|
onChange={(e) =>
|
|
handleChange(field as keyof ContactData, e.target.value)
|
|
}
|
|
required
|
|
className="px-3 py-1.5 border border-gray-400 rounded-md focus:outline-none focus:ring-1 focus:ring-[var(--primary)] text-sm"
|
|
placeholder={`Enter ${label}`}
|
|
/>
|
|
{errors[field] && (
|
|
<span className="text-sm text-red-500 mt-1">{errors[field]}</span>
|
|
)}
|
|
</div>
|
|
))}
|
|
</div>
|
|
|
|
<div className="flex flex-col sm:flex-row justify-end gap-3 mt-4">
|
|
<button
|
|
type="button"
|
|
onClick={() => setShowModal((prev) => !prev)}
|
|
disabled={loading}
|
|
className="bg-gray-300 px-5 py-1.5 rounded-md text-slate-700 text-sm font-medium hover:bg-opacity-90 transition disabled:opacity-60 disabled:cursor-not-allowed cursor-pointer"
|
|
>
|
|
Cancel
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={handleSubmit}
|
|
disabled={loading}
|
|
className="bg-gradient-to-br from-[var(--primary)] to-blue-600 px-5 py-1.5 rounded-md text-white text-sm font-medium hover:bg-opacity-90 transition disabled:opacity-60 disabled:cursor-not-allowed cursor-pointer"
|
|
>
|
|
{loading ? (
|
|
<>
|
|
<FaSpinner className="animate-spin inline-block mr-2" />
|
|
SAVING...
|
|
</>
|
|
) : (
|
|
`${actionStatus?.toUpperCase() || "SAVE"} CONTACT`
|
|
)}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
);
|
|
};
|
|
|
|
export default ContactFormModal;
|