import { useState, useEffect } from 'react'; import { Input } from '@/components/base/input/input'; import { Select } from '@/components/base/select/select'; import { TextArea } from '@/components/base/textarea/textarea'; import { Checkbox } from '@/components/base/checkbox/checkbox'; import { Button } from '@/components/base/buttons/button'; import { apiClient } from '@/lib/api-client'; import { notify } from '@/lib/toast'; type EnquiryFormProps = { isOpen: boolean; onOpenChange: (open: boolean) => void; callerPhone?: string | null; leadId?: string | null; patientId?: string | null; agentName?: string | null; onSaved?: () => void; }; export const EnquiryForm = ({ isOpen, onOpenChange, callerPhone, leadId: propLeadId, patientId, agentName, onSaved }: EnquiryFormProps) => { const [patientName, setPatientName] = useState(''); const [source, setSource] = useState('Phone Inquiry'); const [queryAsked, setQueryAsked] = useState(''); const [isExisting, setIsExisting] = useState(false); const [registeredPhone, setRegisteredPhone] = useState(callerPhone ?? ''); const [department, setDepartment] = useState(null); const [doctor, setDoctor] = useState(null); const [followUpNeeded, setFollowUpNeeded] = useState(false); const [followUpDate, setFollowUpDate] = useState(''); const [isSaving, setIsSaving] = useState(false); const [error, setError] = useState(null); // Fetch doctors for department/doctor dropdowns const [doctors, setDoctors] = useState>([]); useEffect(() => { if (!isOpen) return; apiClient.graphql<{ doctors: { edges: Array<{ node: any }> } }>( `{ doctors(first: 50) { edges { node { id name fullName { firstName lastName } department } } } }`, ).then(data => { setDoctors(data.doctors.edges.map(e => ({ id: e.node.id, name: e.node.fullName ? `Dr. ${e.node.fullName.firstName} ${e.node.fullName.lastName}`.trim() : e.node.name, department: e.node.department ?? '', }))); }).catch(() => {}); }, [isOpen]); const departmentItems = [...new Set(doctors.map(d => d.department).filter(Boolean))] .map(dept => ({ id: dept, label: dept.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase()) })); const filteredDoctors = department ? doctors.filter(d => d.department === department) : doctors; const doctorItems = filteredDoctors.map(d => ({ id: d.id, label: d.name })); const handleSave = async () => { if (!patientName.trim() || !queryAsked.trim()) { setError('Please fill in required fields: patient name and query.'); return; } setIsSaving(true); setError(null); try { // Use passed leadId or resolve from phone let leadId: string | null = propLeadId ?? null; if (!leadId && registeredPhone) { const resolved = await apiClient.post<{ leadId: string; patientId: string }>('/api/caller/resolve', { phone: registeredPhone }, { silent: true }); leadId = resolved.leadId; } if (leadId) { // Update existing lead with enquiry details await apiClient.graphql( `mutation($id: UUID!, $data: LeadUpdateInput!) { updateLead(id: $id, data: $data) { id } }`, { id: leadId, data: { name: `Enquiry — ${patientName}`, contactName: { firstName: patientName.split(' ')[0], lastName: patientName.split(' ').slice(1).join(' ') || '' }, source: 'PHONE', status: 'CONTACTED', interestedService: queryAsked.substring(0, 100), }, }, ); } else { // No phone provided — create a new lead (rare edge case) await apiClient.graphql( `mutation($data: LeadCreateInput!) { createLead(data: $data) { id } }`, { data: { name: `Enquiry — ${patientName}`, contactName: { firstName: patientName.split(' ')[0], lastName: patientName.split(' ').slice(1).join(' ') || '' }, contactPhone: registeredPhone ? { primaryPhoneNumber: registeredPhone } : undefined, source: 'PHONE', status: 'CONTACTED', interestedService: queryAsked.substring(0, 100), }, }, ); } // Update patient name if we have a name and a linked patient if (patientId && patientName.trim()) { await apiClient.graphql( `mutation($id: UUID!, $data: PatientUpdateInput!) { updatePatient(id: $id, data: $data) { id } }`, { id: patientId, data: { fullName: { firstName: patientName.split(' ')[0], lastName: patientName.split(' ').slice(1).join(' ') || '' }, }, }, ).catch((err: unknown) => console.warn('Failed to update patient name:', err)); } // Invalidate caller cache so next lookup gets the real name if (callerPhone) { apiClient.post('/api/caller/invalidate', { phone: callerPhone }, { silent: true }).catch(() => {}); } // Create follow-up if needed if (followUpNeeded) { if (!followUpDate) { setError('Please select a follow-up date.'); setIsSaving(false); return; } await apiClient.graphql( `mutation($data: FollowUpCreateInput!) { createFollowUp(data: $data) { id } }`, { data: { name: `Follow-up — ${patientName}`, typeCustom: 'CALLBACK', status: 'PENDING', priority: 'NORMAL', assignedAgent: agentName ?? undefined, scheduledAt: new Date(`${followUpDate}T09:00:00`).toISOString(), patientId: patientId ?? undefined, }, }, { silent: true }, ); } notify.success('Enquiry Logged', 'Contact details and query captured'); onSaved?.(); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to save enquiry'); } finally { setIsSaving(false); } }; if (!isOpen) return null; return (
{/* Form fields — scrollable */}