'use client'; import * as React from 'react'; import { Button } from '@/components/ui/button'; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from '@/components/ui/dialog'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Textarea } from '@/components/ui/textarea'; import { ApiError } from '@/lib/api-client'; import { useAuthStore } from '@/lib/auth-store'; import { useCreateInquiry } from '@/lib/hooks/use-inquiries'; interface InquiryModalProps { open: boolean; onOpenChange: (open: boolean) => void; listingId: string; listingTitle: string; sellerName: string; } export function InquiryModal({ open, onOpenChange, listingId, listingTitle, sellerName, }: InquiryModalProps) { const { user, isAuthenticated } = useAuthStore(); const createInquiry = useCreateInquiry(); const [message, setMessage] = React.useState(''); const [phone, setPhone] = React.useState(''); const [error, setError] = React.useState(null); const [success, setSuccess] = React.useState(false); // Pre-fill phone from auth store when modal opens React.useEffect(() => { if (open && user?.phone) { setPhone(user.phone); } if (open) { setError(null); setSuccess(false); setMessage(''); } }, [open, user?.phone]); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!isAuthenticated) { window.location.href = '/login'; onOpenChange(false); return; } const trimmedMessage = message.trim(); const trimmedPhone = phone.trim(); if (!trimmedMessage) { setError('Vui long nhap noi dung tin nhan'); return; } if (!trimmedPhone || trimmedPhone.length < 9) { setError('Vui long nhap so dien thoai hop le'); return; } setError(null); try { await createInquiry.mutateAsync({ listingId, message: trimmedMessage, phone: trimmedPhone, }); setSuccess(true); } catch (err) { if (err instanceof ApiError && err.status === 401) { window.location.href = '/login'; onOpenChange(false); return; } setError( err instanceof ApiError ? err.message : 'Gui tin nhan that bai. Vui long thu lai.', ); } }; if (success) { return ( Da gui thanh cong! Tin nhan cua ban da duoc gui den {sellerName}. Ho se lien he voi ban som nhat co the.
); } return ( Nhan tin cho nguoi ban Gui tin nhan ve tin dang “{listingTitle}”
{error && (
{error}
)}