117 lines
2.8 KiB
TypeScript
117 lines
2.8 KiB
TypeScript
import { toast } from "@/hooks/use-toast";
|
|
import { ContactUsInsert } from "@/src/applications/entities/models/contact-us.model";
|
|
import { useState } from "react";
|
|
import { ContactRepositoryImpl } from "../repositories/contact-us.repository.impl";
|
|
import { validateContactForm } from "../validators/contact-us.validator";
|
|
|
|
export const useContactForm = () => {
|
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
|
const [formData, setFormData] = useState<ContactUsInsert>({
|
|
name: "",
|
|
email: "",
|
|
phone: "",
|
|
typeMessage: "",
|
|
message: "",
|
|
});
|
|
const [errors, setErrors] = useState<
|
|
Partial<Record<keyof ContactUsInsert, string>>
|
|
>({});
|
|
|
|
const contactRepository = new ContactRepositoryImpl();
|
|
|
|
// Handle input change
|
|
const handleChange = (
|
|
e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
|
|
) => {
|
|
const { id, value } = e.target;
|
|
setFormData((prev) => ({ ...prev, [id]: value }));
|
|
|
|
if (errors[id as keyof ContactUsInsert]) {
|
|
setErrors((prev) => {
|
|
const newErrors = { ...prev };
|
|
delete newErrors[id as keyof ContactUsInsert];
|
|
return newErrors;
|
|
});
|
|
}
|
|
};
|
|
|
|
// Handle select change
|
|
const handleSelectChange = (value: string) => {
|
|
setFormData((prev) => ({ ...prev, typeMessage: value }));
|
|
|
|
// Clear error when selecting
|
|
if (errors.typeMessage) {
|
|
setErrors((prev) => {
|
|
const newErrors = { ...prev };
|
|
delete newErrors.typeMessage;
|
|
return newErrors;
|
|
});
|
|
}
|
|
};
|
|
|
|
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
|
e.preventDefault();
|
|
|
|
// Client-side validation
|
|
const validation = validateContactForm(formData);
|
|
|
|
if (!validation.success) {
|
|
setErrors(validation.errors);
|
|
return;
|
|
}
|
|
|
|
setIsSubmitting(true);
|
|
|
|
try {
|
|
const response = await contactRepository.createContactUs(formData);
|
|
|
|
if (!response.success) {
|
|
if (response.errors) {
|
|
setErrors(response.errors);
|
|
} else {
|
|
toast({
|
|
title: "Error",
|
|
description: response.error || "Failed to send message",
|
|
variant: "destructive",
|
|
});
|
|
}
|
|
return;
|
|
}
|
|
|
|
toast({
|
|
title: "Success",
|
|
description:
|
|
response.message || "Your message has been sent successfully!",
|
|
});
|
|
|
|
// Reset form
|
|
setFormData({
|
|
name: "",
|
|
email: "",
|
|
phone: "",
|
|
typeMessage: "",
|
|
message: "",
|
|
});
|
|
setErrors({});
|
|
} catch (error) {
|
|
toast({
|
|
title: "Error",
|
|
description: "An unexpected error occurred. Please try again later.",
|
|
variant: "destructive",
|
|
});
|
|
} finally {
|
|
setIsSubmitting(false);
|
|
}
|
|
};
|
|
|
|
return {
|
|
formData,
|
|
errors,
|
|
isSubmitting,
|
|
setFormData,
|
|
handleChange,
|
|
handleSelectChange,
|
|
handleSubmit,
|
|
};
|
|
};
|