import React, { useEffect } from 'react'; import { UnitControl } from "../ui/unit-control"; import { Controller, useFormContext } from 'react-hook-form'; import { IValueSet, useValueSetServiceContext } from '../../services'; interface FhirAgeProps { label?: string; context: string; disabled?: boolean; defaultValue?: { value?: number; unit?: string; }; onChange?: (value: { value: number, unit: string }) => void; } const FhirAge: React.FC = ({ context, label = 'Age', disabled = false, defaultValue, onChange }) => { const { control, setValue, getValues, watch } = useFormContext(); const { ageUnits } = useValueSetServiceContext(); const ageValue = watch(`${context}.value`); const ageUnit = watch(`${context}.unit`); useEffect(() => { if (defaultValue) { setValue(`${context}.value`, defaultValue.value ?? 1); setValue(`${context}.unit`, defaultValue.unit ?? 'years'); } }, [defaultValue, setValue, context]); useEffect(() => { if (onChange && ageValue !== undefined && ageUnit !== undefined) { onChange({ value: Number(ageValue), unit: ageUnit }); } }, [ageValue, ageUnit, onChange]); return ( <> { const currentUnit = getValues(`${context}.unit`) || 'years'; return ( { if (!value) { field.onChange(0); return; } const numericValue = value.replace(currentUnit, ''); field.onChange(Number(numericValue) || 0); }} onUnitChange={(unit: string | undefined) => { const newUnit = unit || 'years'; setValue(`${context}.unit`, newUnit); }} units={ageUnits.map((option: IValueSet) => ( { label: option.display, value: option.display } ))}/> ); }}/> ); }; export default FhirAge;