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 { Button } from '@/components/base/buttons/button'; import { DatePicker } from '@/components/application/date-picker/date-picker'; import { parseDate } from '@internationalized/date'; import { apiClient } from '@/lib/api-client'; import { cx } from '@/utils/cx'; import { notify } from '@/lib/toast'; type ExistingAppointment = { id: string; scheduledAt: string; doctorName: string; doctorId?: string; department: string; reasonForVisit?: string; status: string; }; type AppointmentFormProps = { isOpen: boolean; onOpenChange: (open: boolean) => void; callerNumber?: string | null; leadName?: string | null; leadId?: string | null; patientId?: string | null; onSaved?: () => void; existingAppointment?: ExistingAppointment | null; }; type DoctorRecord = { id: string; name: string; department: string; clinic: string }; const clinicItems = [ { id: 'koramangala', label: 'Global Hospital - Koramangala' }, { id: 'whitefield', label: 'Global Hospital - Whitefield' }, { id: 'indiranagar', label: 'Global Hospital - Indiranagar' }, ]; const genderItems = [ { id: 'male', label: 'Male' }, { id: 'female', label: 'Female' }, { id: 'other', label: 'Other' }, ]; const timeSlotItems = [ { id: '09:00', label: '9:00 AM' }, { id: '09:30', label: '9:30 AM' }, { id: '10:00', label: '10:00 AM' }, { id: '10:30', label: '10:30 AM' }, { id: '11:00', label: '11:00 AM' }, { id: '11:30', label: '11:30 AM' }, { id: '14:00', label: '2:00 PM' }, { id: '14:30', label: '2:30 PM' }, { id: '15:00', label: '3:00 PM' }, { id: '15:30', label: '3:30 PM' }, { id: '16:00', label: '4:00 PM' }, ]; const formatDeptLabel = (dept: string) => dept.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase()); export const AppointmentForm = ({ isOpen, onOpenChange, callerNumber, leadName, leadId, patientId, onSaved, existingAppointment, }: AppointmentFormProps) => { const isEditMode = !!existingAppointment; // Doctor data from platform const [doctors, setDoctors] = useState([]); // Form state — initialized from existing appointment in edit mode const [patientName, setPatientName] = useState(leadName ?? ''); const [patientPhone, setPatientPhone] = useState(callerNumber ?? ''); const [age, setAge] = useState(''); const [gender, setGender] = useState(null); const [clinic, setClinic] = useState(null); const [department, setDepartment] = useState(existingAppointment?.department ?? null); const [doctor, setDoctor] = useState(existingAppointment?.doctorId ?? null); const [date, setDate] = useState(() => { if (existingAppointment?.scheduledAt) return existingAppointment.scheduledAt.split('T')[0]; return new Date().toISOString().split('T')[0]; }); const [timeSlot, setTimeSlot] = useState(() => { if (existingAppointment?.scheduledAt) { const dt = new Date(existingAppointment.scheduledAt); return `${dt.getHours().toString().padStart(2, '0')}:${dt.getMinutes().toString().padStart(2, '0')}`; } return null; }); const [chiefComplaint, setChiefComplaint] = useState(existingAppointment?.reasonForVisit ?? ''); const [source, setSource] = useState('Inbound Call'); const [agentNotes, setAgentNotes] = useState(''); // Availability state const [bookedSlots, setBookedSlots] = useState([]); const [loadingSlots, setLoadingSlots] = useState(false); const [isSaving, setIsSaving] = useState(false); const [error, setError] = useState(null); // Fetch doctors on mount useEffect(() => { if (!isOpen) return; apiClient.graphql<{ doctors: { edges: Array<{ node: any }> } }>( `{ doctors(first: 50) { edges { node { id name fullName { firstName lastName } department clinic { id name clinicName } } } } }`, ).then(data => { const docs = 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 ?? '', clinic: e.node.clinic?.clinicName ?? e.node.clinic?.name ?? '', })); setDoctors(docs); }).catch(() => {}); }, [isOpen]); // Fetch booked slots when doctor + date selected useEffect(() => { if (!doctor || !date) { setBookedSlots([]); return; } setLoadingSlots(true); apiClient.graphql<{ appointments: { edges: Array<{ node: any }> } }>( `{ appointments(filter: { doctorId: { eq: "${doctor}" }, scheduledAt: { gte: "${date}T00:00:00", lte: "${date}T23:59:59" } }) { edges { node { id scheduledAt durationMin status } } } }`, ).then(data => { // Filter out cancelled/completed appointments client-side const activeAppointments = data.appointments.edges.filter(e => { const status = e.node.status; return status !== 'CANCELLED' && status !== 'COMPLETED' && status !== 'NO_SHOW'; }); const slots = activeAppointments.map(e => { const dt = new Date(e.node.scheduledAt); return `${dt.getHours().toString().padStart(2, '0')}:${dt.getMinutes().toString().padStart(2, '0')}`; }); // In edit mode, don't block the current appointment's slot if (isEditMode && existingAppointment) { const currentDt = new Date(existingAppointment.scheduledAt); const currentSlot = `${currentDt.getHours().toString().padStart(2, '0')}:${currentDt.getMinutes().toString().padStart(2, '0')}`; setBookedSlots(slots.filter(s => s !== currentSlot)); } else { setBookedSlots(slots); } }).catch(() => setBookedSlots([])) .finally(() => setLoadingSlots(false)); }, [doctor, date, isEditMode, existingAppointment]); // Reset doctor when department changes useEffect(() => { setDoctor(null); setTimeSlot(null); }, [department]); // Reset time slot when doctor or date changes useEffect(() => { setTimeSlot(null); }, [doctor, date]); // Derive department and doctor lists from fetched data const departmentItems = [...new Set(doctors.map(d => d.department).filter(Boolean))] .map(dept => ({ id: dept, label: formatDeptLabel(dept) })); const filteredDoctors = department ? doctors.filter(d => d.department === department) : doctors; const doctorSelectItems = filteredDoctors.map(d => ({ id: d.id, label: d.name })); const timeSlotSelectItems = timeSlotItems.map(slot => ({ ...slot, isDisabled: bookedSlots.includes(slot.id), label: bookedSlots.includes(slot.id) ? `${slot.label} (Booked)` : slot.label, })); const handleSave = async () => { if (!date || !timeSlot || !doctor || !department) { setError('Please fill in the required fields: date, time, doctor, and department.'); return; } const today = new Date().toISOString().split('T')[0]; if (!isEditMode && date < today) { setError('Appointment date cannot be in the past.'); return; } setIsSaving(true); setError(null); try { const scheduledAt = new Date(`${date}T${timeSlot}:00`).toISOString(); const selectedDoctor = doctors.find(d => d.id === doctor); if (isEditMode && existingAppointment) { // Update existing appointment await apiClient.graphql( `mutation UpdateAppointment($id: UUID!, $data: AppointmentUpdateInput!) { updateAppointment(id: $id, data: $data) { id } }`, { id: existingAppointment.id, data: { scheduledAt, doctorName: selectedDoctor?.name ?? '', department: selectedDoctor?.department ?? '', doctorId: doctor, reasonForVisit: chiefComplaint || null, }, }, ); notify.success('Appointment Updated'); } else { // Create appointment await apiClient.graphql( `mutation CreateAppointment($data: AppointmentCreateInput!) { createAppointment(data: $data) { id } }`, { data: { scheduledAt, durationMin: 30, appointmentType: 'CONSULTATION', status: 'SCHEDULED', doctorName: selectedDoctor?.name ?? '', department: selectedDoctor?.department ?? '', doctorId: doctor, reasonForVisit: chiefComplaint || null, ...(patientId ? { patientId } : {}), }, }, ); // Update patient name if we have a name and a linked patient if (patientId && patientName.trim()) { await apiClient.graphql( `mutation UpdatePatient($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)); } // Update lead status + name if we have a matched lead if (leadId) { await apiClient.graphql( `mutation UpdateLead($id: UUID!, $data: LeadUpdateInput!) { updateLead(id: $id, data: $data) { id } }`, { id: leadId, data: { leadStatus: 'APPOINTMENT_SET', lastContactedAt: new Date().toISOString(), ...(patientName.trim() ? { contactName: { firstName: patientName.split(' ')[0], lastName: patientName.split(' ').slice(1).join(' ') || '' } } : {}), }, }, ).catch((err: unknown) => console.warn('Failed to update lead:', err)); } // Invalidate caller cache so next lookup gets the real name if (callerNumber) { apiClient.post('/api/caller/invalidate', { phone: callerNumber }, { silent: true }).catch(() => {}); } } onSaved?.(); } catch (err) { console.error('Failed to save appointment:', err); setError(err instanceof Error ? err.message : 'Failed to save appointment. Please try again.'); } finally { setIsSaving(false); } }; const handleCancel = async () => { if (!existingAppointment) return; setIsSaving(true); try { await apiClient.graphql( `mutation CancelAppointment($id: UUID!, $data: AppointmentUpdateInput!) { updateAppointment(id: $id, data: $data) { id } }`, { id: existingAppointment.id, data: { status: 'CANCELLED' }, }, ); notify.success('Appointment Cancelled'); onSaved?.(); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to cancel appointment'); } finally { setIsSaving(false); } }; if (!isOpen) return null; return (
{/* Form fields — scrollable */}
{/* Patient Info — only for new appointments */} {!isEditMode && ( <>
Patient Information
)} {/* Appointment Details */}
Appointment Details
{!isEditMode && ( )}
Date * setDate(val ? val.toString() : '')} granularity="day" />
{/* Time slot grid */} {doctor && date && (
{loadingSlots ? 'Checking availability...' : 'Available Slots'}
{timeSlotSelectItems.map(slot => { const isBooked = slot.isDisabled; const isSelected = timeSlot === slot.id; return ( ); })}
)} {!doctor || !date ? (

Select a doctor and date to see available time slots

) : null}