Files
PVHFrontend/src/components/ModalRequestForm/ModalRequestForm.tsx
T
2026-04-06 21:18:00 +03:00

192 lines
5.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import React from "react";
import { Modal } from "antd";
import { motion } from "framer-motion";
import InputMask from "react-input-mask";
import { useForm } from "react-hook-form";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import styles from "./ModalRequestForm.module.css";
import Button from "../Button/Button";
import { client } from "../../api/client";
// ✅ Схема валидации
const schema = yup.object().shape({
name: yup.string().required("Введите имя"),
email: yup.string().email("Некорректный Email").required("Введите Email"),
phone: yup.string().min(18, "Введите корректный номер").required("Введите номер"),
message: yup.string().nullable(),
});
interface Props {
open: boolean;
onClose: () => void;
}
interface FormData {
name: string;
email: string;
phone: string;
message?: string | null;
}
const ModalRequestForm: React.FC<Props> = ({ open, onClose }) => {
console.log('ModalRequestForm render, open:', open);
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
reset,
} = useForm({ resolver: yupResolver(schema) });
const handlePhoneInput = (e: React.ChangeEvent<HTMLInputElement>) => {
let value = e.target.value.replace(/\D/g, '');
if (value.startsWith('7') || value.startsWith('8')) {
value = value.substring(1);
}
let formattedValue = '+7 ';
if (value.length > 0) {
formattedValue += '(' + value.substring(0, 3);
}
if (value.length > 3) {
formattedValue += ') ' + value.substring(3, 6);
}
if (value.length > 6) {
formattedValue += '-' + value.substring(6, 8);
}
if (value.length > 8) {
formattedValue += '-' + value.substring(8, 10);
}
e.target.value = formattedValue;
};
// ✅ Отправка данных на бэкенд
const sendToBackend = async (data: FormData): Promise<boolean> => {
try {
const payload = {
...data,
};
const response = await client.post<{ success: boolean }>("/email/", payload);
return response.data.success;
} catch (error) {
console.error("Error sending request:", error);
throw new Error("Не удалось отправить заявку. Попробуйте позже.");
}
};
// ✅ Submit
const onSubmit = async (data: FormData) => {
try {
await sendToBackend(data);
// Показываем уведомление об успехе
Modal.success({
title: "Заявка отправлена!",
content: "Наш менеджер свяжется с вами в ближайшее время.",
okText: "Хорошо",
});
reset();
onClose();
} catch (error) {
// Показываем ошибку
Modal.error({
title: "Ошибка",
content: error instanceof Error ? error.message : "Произошла неизвестная ошибка",
okText: "Понятно",
});
}
};
return (
<Modal
open={open}
footer={null}
onCancel={onClose}
centered
width={620}
closable={!isSubmitting}
maskClosable={!isSubmitting}
>
<motion.div
initial={{ opacity: 0, y: 40 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.35 }}
className={styles.modalBox}
>
<h2 className={styles.title}>Контрактное производство</h2>
<p className={styles.subtitle}>
Заполните форму ниже, и наш менеджер свяжется с Вами
</p>
<form onSubmit={handleSubmit(onSubmit)} className={styles.form}>
<div className={styles.field}>
<input
className={styles.input}
placeholder="Введите имя *"
{...register("name")}
disabled={isSubmitting}
/>
{errors.name && <span className={styles.error}>{errors.name.message}</span>}
</div>
<div className={styles.field}>
<input
className={styles.input}
placeholder="Введите email *"
{...register("email")}
disabled={isSubmitting}
/>
{errors.email && <span className={styles.error}>{errors.email.message}</span>}
</div>
{/*<div className={styles.field}>
<InputMask
mask="+7 (999) 999-99-99"
{...register("phone")}
disabled={isSubmitting}
>
{(inputProps: any) => (
<input
className={styles.input}
placeholder="Введите № телефона *"
{...inputProps}
/>
)}
</InputMask>
{errors.phone && <span className={styles.error}>{errors.phone.message}</span>}
</div>*/}
<div className={styles.field}>
<input
className={styles.input}
placeholder="+7 (___) ___-__-__ *"
{...register("phone")}
onInput={handlePhoneInput}
disabled={isSubmitting}
/>
{errors.phone && <span className={styles.error}>{errors.phone.message}</span>}
</div>
<textarea
className={styles.textarea}
placeholder="Задайте свой вопрос"
{...register("message")}
disabled={isSubmitting}
/>
<Button
label={isSubmitting ? "ОТПРАВКА..." : "СДЕЛАТЬ ЗАПРОС"}
className={styles.button}
/>
</form>
</motion.div>
</Modal>
);
};
export default ModalRequestForm;