All files / src/features/medications/components MedicationEditorDialog.tsx

81.57% Statements 62/76
84.87% Branches 101/119
66.66% Functions 12/18
87.69% Lines 57/65

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324                                                                                    91x 91x 91x 91x 91x 91x 91x 10x 3x 3x 3x 3x     91x 91x 91x 91x 91x 91x 91x 91x             91x                         91x       91x 91x   3x 3x 3x 3x 2x   1x 1x   2x     3x       91x 2x 2x 2x 2x   1x 1x   1x 1x   91x     91x                                 182x                       88x           2x 1x 1x                                                               5x 5x                                                               3x         3x                                                                                           1x 1x                                                                       2x 2x                      
import { zodResolver } from '@hookform/resolvers/zod'
import { useEffect, useRef, useState } from 'react'
import { useForm, useWatch } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import {
  AlertDialog,
  AlertDialogContent,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogCancel,
  AlertDialogAction,
} from '@/components/ui/alert-dialog'
import { useBabies } from '@/features/babies/api/babies.hooks'
import { useSpecialistsForBaby } from '@/features/specialists/api/specialists.hooks'
import { todayDateString, formatDateDisplay } from '@/lib/date'
import { BabyPickerStep } from '@/shared/components/BabyPickerStep'
import {
  useCreateMedication,
  useUpdateMedication,
  useDeleteMedication,
} from '../api/medications.hooks'
import {
  medicationFormSchema,
  type Medication,
  type MedicationFormInput,
} from '../api/medications.schemas'
import { MedicationDialogLayout } from './MedicationDialogLayout'
import { MedicationFields } from './MedicationFields'
import { MedicationRecordNotice } from './MedicationRecordNotice'
 
type Step = 'baby' | 'medicine' | 'details'
export function MedicationEditorDialog({
  medication,
  onOpenChange,
}: {
  medication?: Medication
  onOpenChange: (open: boolean) => void
}) {
  const { t, i18n } = useTranslation()
  const babies = useBabies()
  const babyList = babies.data ?? []
  const [babyId, setBabyId] = useState<string | null>(medication?.babyId ?? null)
  const [step, setStep] = useState<Step>(medication ? 'medicine' : 'baby')
  const initialized = useRef(!!medication)
  useEffect(() => {
    if (initialized.current || !babies.isSuccess) return
    initialized.current = true
    Eif (babies.data.length === 1) {
      setBabyId(babies.data[0]!.id)
      setStep('medicine')
    }
  }, [babies.data, babies.isSuccess])
  const baby = babyList.find((item) => item.id === babyId)
  const specialists = useSpecialistsForBaby(babyId)
  const create = useCreateMedication(babyId)
  const update = useUpdateMedication(babyId ?? '')
  const remove = useDeleteMedication(babyId ?? '')
  const [deleteOpen, setDeleteOpen] = useState(false)
  const [error, setError] = useState(false)
  const [deleteError, setDeleteError] = useState(false)
  const {
    register,
    control,
    trigger,
    handleSubmit,
    formState: { errors, isDirty, isSubmitting },
  } = useForm<MedicationFormInput>({
    resolver: zodResolver(medicationFormSchema),
    defaultValues: {
      name: medication?.name ?? '',
      dosage: medication?.dosage ?? '',
      frequency: medication?.frequency ?? '',
      startedOn: medication?.startedOn ?? todayDateString(),
      endedOn: medication?.endedOn ?? '',
      reason: medication?.reason ?? '',
      prescriberName: medication?.prescriberName ?? '',
      notes: medication?.notes ?? '',
    },
  })
  const [name, dosage, frequency, startedOn, endedOn] = useWatch({
    control,
    name: ['name', 'dosage', 'frequency', 'startedOn', 'endedOn'],
  })
  const busy = isSubmitting || create.isPending || update.isPending || remove.isPending
  const save = handleSubmit(
    async (values) => {
      Iif (!babyId || busy) return
      setError(false)
      try {
        if (medication) await update.mutateAsync({ medicationId: medication.id, input: values })
        else await create.mutateAsync(values)
      } catch {
        setError(true)
        return
      }
      toast.success(
        t(medication ? 'medications.form.updateSuccessToast' : 'medications.form.successToast'),
      )
      onOpenChange(false)
    },
    (invalid) => setStep(invalid.name ? 'medicine' : 'details'),
  )
  const deleteRecord = async () => {
    Iif (!medication || busy) return
    setDeleteError(false)
    try {
      await remove.mutateAsync(medication.id)
    } catch {
      setDeleteError(true)
      return
    }
    toast.success(t('medications.deleteSuccessToast'))
    onOpenChange(false)
  }
  const period = startedOn
    ? `${formatDateDisplay(startedOn, i18n.language)} ยท ${endedOn ? formatDateDisplay(endedOn, i18n.language) : t('medications.editor.noEnd')}`
    : undefined
  return (
    <>
      <MedicationDialogLayout
        open
        onOpenChange={onOpenChange}
        title={t(medication ? 'medications.form.editTitle' : 'medications.form.createTitle')}
        baby={baby}
        medicine={name}
        dosage={dosage}
        frequency={frequency}
        date={period}
        stage={step}
        dirty={isDirty}
        busy={busy}
        progress={
          <ol className="flex flex-wrap gap-x-5 gap-y-2">
            {(['medicine', 'details'] as const).map((item, index) => (
              <li
                key={item}
                aria-current={step === item ? 'step' : undefined}
                className={`text-sm font-semibold ${step === item ? 'text-sky-800 dark:text-sky-300' : 'text-ink-muted'}`}
              >
                <span className="mr-2 text-xs">0{index + 1}</span>
                {t(`medications.editor.${item}`)}
              </li>
            ))}
          </ol>
        }
        footer={(close) => (
          <>
            <Button
              type="button"
              variant="ghost"
              disabled={busy}
              onClick={() => {
                if (step === 'details') setStep('medicine')
                else Iif (step === 'medicine' && !medication && babyList.length > 1) setStep('baby')
                else close()
              }}
            >
              {t(
                step === 'details' || (step === 'medicine' && !medication && babyList.length > 1)
                  ? 'medications.wizard.back'
                  : 'common.cancel',
              )}
            </Button>
            {step === 'details' ? (
              <Button
                key="save"
                type="submit"
                form="medication-editor-form"
                disabled={busy || !babyId}
                className="bg-sky-800 text-white hover:bg-sky-900"
              >
                {t(
                  busy
                    ? 'common.saving'
                    : medication
                      ? 'medications.form.updateSubmit'
                      : 'medications.form.submit',
                )}
              </Button>
            ) : (
              <Button
                key="continue"
                type="button"
                disabled={busy || !babyId || !babies.isSuccess}
                className="bg-sky-800 text-white hover:bg-sky-900"
                onClick={async () => {
                  Iif (step === 'baby') setStep('medicine')
                  else if (await trigger('name', { shouldFocus: true })) setStep('details')
                }}
              >
                {t('medications.wizard.continue')}
              </Button>
            )}
          </>
        )}
      >
        {babies.isPending ? (
          <p role="status">{t('common.loading')}</p>
        ) : babies.isError ? (
          <div role="alert" className="space-y-3">
            <p>{t('medications.editor.childrenError')}</p>
            <Button
              type="button"
              onClick={() => {
                void babies.refetch()
              }}
            >
              {t('medications.editor.retry')}
            </Button>
          </div>
        ) : !babyList.length ? (
          <p>{t('medications.editor.noChildren')}</p>
        ) : step === 'baby' ? (
          <BabyPickerStep babies={babyList} value={babyId} onSelect={setBabyId} />
        ) : (
          <>
            <form
              id="medication-editor-form"
              onSubmit={(event) => {
                Iif (step === 'medicine') {
                  event.preventDefault()
                  void trigger('name', { shouldFocus: true }).then((valid) => {
                    if (valid) setStep('details')
                  })
                } else void save(event)
              }}
              noValidate
              className="space-y-5"
            >
              {step === 'medicine' && <MedicationRecordNotice />}
              <MedicationFields
                register={register}
                control={control}
                errors={errors}
                section={step}
                prescribers={specialists.data?.map((person) => person.name)}
              />
              {step === 'details' && specialists.isPending && (
                <p role="status" className="text-sm text-ink-muted">
                  {t('medications.editor.loadingPrescribers')}
                </p>
              )}
              {step === 'details' && specialists.isError && (
                <div role="alert" className="space-y-2 text-sm">
                  <p>{t('medications.editor.prescribersError')}</p>
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => {
                      void specialists.refetch()
                    }}
                  >
                    {t('medications.editor.retry')}
                  </Button>
                </div>
              )}
              {error && (
                <p role="alert" className="text-sm text-destructive">
                  {t('medications.form.genericError')}
                </p>
              )}
            </form>
            {medication && step === 'details' && (
              <div className="mt-6 border-t border-border pt-4">
                <Button
                  type="button"
                  variant="ghost"
                  className="text-destructive"
                  disabled={busy}
                  onClick={() => {
                    setDeleteError(false)
                    setDeleteOpen(true)
                  }}
                >
                  {t('medications.deleteAction')}
                </Button>
              </div>
            )}
          </>
        )}
      </MedicationDialogLayout>
      <AlertDialog
        open={deleteOpen}
        onOpenChange={(open) => {
          if (!busy) setDeleteOpen(open)
        }}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t('medications.deleteConfirmTitle')}</AlertDialogTitle>
            <AlertDialogDescription>
              {t('medications.deleteConfirmDescription', { name: medication?.name })}
            </AlertDialogDescription>
          </AlertDialogHeader>
          {deleteError && (
            <p role="alert" className="text-sm text-destructive">
              {t('medications.form.genericError')}
            </p>
          )}
          <AlertDialogFooter>
            <AlertDialogCancel disabled={busy}>
              {t('medications.deleteConfirmDismiss')}
            </AlertDialogCancel>
            <AlertDialogAction
              variant="destructive"
              disabled={busy}
              onClick={(event) => {
                event.preventDefault()
                void deleteRecord()
              }}
            >
              {t(busy ? 'common.saving' : 'medications.deleteConfirmAction')}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  )
}