Files
tripwithbonus/frontend/components/popups/LeadPopup.tsx
2025-05-27 15:07:33 +03:00

150 lines
4.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, { useEffect } from 'react'
import Modal from '../ui/Modal'
import Button from '../ui/Button'
import { useForm } from '@/app/hooks/useForm'
import showToast from '../ui/Toast'
import TextInput from '../ui/TextInput'
import TextAreaInput from '../ui/TextAreaInput'
import PhoneInput from '../ui/PhoneInput'
import useUserStore from '@/app/store/userStore'
import { sendLead } from '@/lib/main/sendLead'
const validationRules = {
name: { required: true },
phone_number: { required: true },
email: { required: true },
moving_price: { required: true },
moving_date: { required: true },
comment: { required: false },
}
interface LeadPopupProps {
id: number
isOpen: boolean
onClose: () => void
onSuccess: () => void
}
const LeadPopup = ({ id, isOpen, onClose, onSuccess }: LeadPopupProps) => {
const { user } = useUserStore()
const today = new Date().toISOString().split('T')[0]
const initialValues = {
name: user?.name || '',
phone_number: user?.phone_number || '',
email: user?.email || '',
moving_price: '',
moving_date: '',
comment: '',
id: id,
}
const { values, handleChange, handleSubmit, setValues } = useForm(
initialValues,
validationRules,
async values => {
try {
await sendLead(values)
showToast({
type: 'success',
message: 'Сообщение отправлено!',
})
onSuccess()
} catch {
showToast({
type: 'error',
message: 'Упс, что то пошло не так...',
})
}
}
)
//форма инициализируется до того, как данные пользователя загружаются из стора, поэтому нужно обновлять значения формы при загрузке данных пользователя
useEffect(() => {
if (user) {
setValues(prev => ({
...prev,
name: user.name,
phone_number: user.phone_number || '',
email: user.email || '',
}))
}
}, [user, setValues])
return (
<Modal title="Откликнуться на заявку" isOpen={isOpen} onClose={onClose}>
<div className="px-6 pb-6">
<form className="space-y-6" onSubmit={handleSubmit}>
<div className="grid grid-cols-1 gap-6">
<div className="space-y-4">
<TextInput
name="name"
value={values.name}
handleChange={handleChange}
label="ФИО"
placeholder="Введите ваше полное имя"
style="register"
/>
<PhoneInput
value={values.phone_number}
handleChange={handleChange}
operatorsInfo={false}
/>
<TextInput
name="email"
value={values.email}
handleChange={handleChange}
label="Email"
placeholder="example@mail.com"
style="register"
/>
<TextInput
name="moving_price"
value={values.moving_price}
handleChange={handleChange}
label="Предлагаемая цена"
placeholder="Укажите стоимость перевозки"
style="register"
/>
<div>
<label htmlFor="moving_date" className="block text-sm font-medium text-gray-700">
Срок доставки
</label>
<input
type="date"
name="moving_date"
id="moving_date"
value={values.moving_date}
onChange={handleChange}
min={today}
className="mt-1 block w-full rounded-xl border border-gray-300 px-3 py-2 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 focus:outline-none"
/>
</div>
<TextAreaInput
name="comment"
value={values.comment}
handleChange={handleChange}
label="Комментарий (необязательно)"
placeholder="Опишите условия перевозки, детали и другую важную информацию"
height={100}
/>
</div>
</div>
<Button
text="Отправить заявку"
className="bg-orange hover:bg-opacity-90 flex w-full justify-center rounded-xl py-4 text-base font-semibold text-white transition-colors"
type="submit"
/>
</form>
</div>
</Modal>
)
}
export default LeadPopup