import React, { useState, useEffect, useCallback } from 'react'; import { Flex, FlexItem } from '../components/ui/flex'; import { DismissibleAlert } from '../components/ui/dismissible-alert'; import { Modal } from '../components/ui/wp-modal-shim'; import { useForm, FormProvider } from 'react-hook-form'; import { MedicationStatement } from 'fhir/r4'; import { useMedicationStatementServiceContext, usePatientServiceContext } from '../services'; import { FhirMedicationStatement } from '../components'; import { useFhirMedicationStatementTargetedBroadcast } from '../hooks'; import { describeWriteFailure } from '../utils/fetchFailureMessage'; import { invalidSubmitMessage } from '../utils/forms/invalidSubmitMessage'; interface MedicationStatementModalProps { isOpen: boolean; onClose: () => void; medicationStatement?: MedicationStatement; onSuccess?: (medicationStatement: MedicationStatement) => void; onError?: (error: string) => void; title?: string; } export const MedicationStatementModal: React.FC = ({ isOpen, onClose, medicationStatement, onSuccess, onError, title }) => { const { patientState, encounterState } = usePatientServiceContext(); const { transformToFhirMedicationStatement, transformFromFhirMedicationStatement, createMedicationStatement, updateMedicationStatement } = useMedicationStatementServiceContext(); const [submitting, setSubmitting] = useState(false); const [success, setSuccess] = useState(); const [error, setError] = useState(); const isNew = !medicationStatement; const modalTitle = title || `${isNew ? 'Create' : 'Edit'} Medication Statement`; const methods = useForm({ defaultValues: { status: '', statusReason: null, category: null, medicationCodeableConcept: null, effectiveType: 'dateTime', effectiveDateTime: '', dateAsserted: '', informationSource: null, reasonCode: [], reasonReference: [], context: [], partOf: [], basedOn: [], note: [], dosage: [] } }); const { handleSubmit, reset } = methods; // A REFUSED CLICK SAYS SO WHERE IT HAPPENED. The button is in the modal header, above a form that // can be several screens tall, and react-hook-form reports each problem inline beside its field - // so somebody scrolled past the first card saw nothing change at all. This fills the error slot // this modal already has, at the top of the form, next to the button they pressed. const onInvalid = (errors: unknown) => setError(invalidSubmitMessage(errors)); const init = useCallback((medicationStatement: MedicationStatement) => { reset(transformFromFhirMedicationStatement(medicationStatement)); }, [transformFromFhirMedicationStatement, reset]); useFhirMedicationStatementTargetedBroadcast({ medicationStatement, isOpen, onUpdate: init, onDelete: onClose }); useEffect(() => { if (medicationStatement) { init(medicationStatement); } }, [medicationStatement, init]); const onSubmit = async (data: any) => { if (!patientState) { const errorMsg = 'Patient information is missing. Please try again.'; setError(errorMsg); onError?.(errorMsg); return; } setSubmitting(true); setSuccess(undefined); setError(undefined); try { let result: MedicationStatement; if (isNew) { result = await createMedicationStatement(transformToFhirMedicationStatement(data, patientState, encounterState)); } else { result = await updateMedicationStatement({ id: medicationStatement?.id, ...transformToFhirMedicationStatement(data, patientState) }, medicationStatement?.meta?.versionId); } const successMsg = `Medication statement ${isNew ? 'created' : 'updated'} successfully.`; setSuccess(successMsg); onSuccess?.(result); setTimeout(() => { setSuccess(undefined); onClose(); }, 1500); } catch (err: any) { console.error(`Error ${isNew ? 'creating' : 'updating'} medication statement:`, err); const errorMsg = describeWriteFailure(err, `Failed to ${isNew ? 'create' : 'update'} medication statement`); setError(errorMsg); onError?.(errorMsg); } finally { setSubmitting(false); } }; if (!isOpen) return null; return ( ]} >
{success && ( setSuccess(undefined)} className="mb-4"> {success} )} {error && ( setError(undefined)} className="mb-4"> {error} )}
); };