import { defineStore } from 'pinia'
import { ref } from 'vue'
import { post } from '../api/client'
import type {
  LiveCaptureObservationInput,
  LiveCaptureResponse,
} from '../types'

export const useLiveCaptureStore = defineStore('liveCapture', () => {
  const loading = ref(false)
  const error = ref<string | null>(null)
  const lastResult = ref<LiveCaptureResponse | null>(null)

  async function recordObservations(
    encounterId: string,
    observations: LiveCaptureObservationInput[],
    clinicianAttestation: boolean,
    passwordConfirm: string,
  ): Promise<LiveCaptureResponse> {
    loading.value = true
    error.value = null
    lastResult.value = null
    try {
      const response = await post<LiveCaptureResponse>(
        `live-capture/encounters/${encounterId}/observations`,
        {
          observations: observations.map(o => ({
            observationCode: o.observationCode,
            value: o.value,
            unit: o.unit,
            recordedAt: o.recordedAt,
            note: o.note || null,
          })),
          clinicianAttestation,
          passwordConfirm,
        },
      )
      if (!response.success || !response.data) {
        throw new Error(response.error?.message ?? 'Failed to record observations')
      }
      lastResult.value = response.data
      return response.data
    } catch (e: unknown) {
      const msg = e instanceof Error ? e.message : 'Failed to record observations'
      error.value = msg
      throw e
    } finally {
      loading.value = false
    }
  }

  async function openEncounterWithVitals(
    patientId: string,
    department: string,
    roomBed: string,
    admissionReason: string,
    observations: LiveCaptureObservationInput[],
    clinicianAttestation: boolean,
    passwordConfirm: string,
  ): Promise<LiveCaptureResponse> {
    loading.value = true
    error.value = null
    lastResult.value = null
    try {
      const response = await post<LiveCaptureResponse>(
        'live-capture/encounters',
        {
          patientId,
          department,
          roomBed: roomBed || null,
          admissionReason,
          observations: observations.map(o => ({
            observationCode: o.observationCode,
            value: o.value,
            unit: o.unit,
            recordedAt: o.recordedAt,
            note: o.note || null,
          })),
          clinicianAttestation,
          passwordConfirm,
        },
      )
      if (!response.success || !response.data) {
        throw new Error(response.error?.message ?? 'Failed to open encounter')
      }
      lastResult.value = response.data
      return response.data
    } catch (e: unknown) {
      const msg = e instanceof Error ? e.message : 'Failed to open encounter'
      error.value = msg
      throw e
    } finally {
      loading.value = false
    }
  }

  function reset() {
    lastResult.value = null
    error.value = null
  }

  return {
    loading,
    error,
    lastResult,
    recordObservations,
    openEncounterWithVitals,
    reset,
  }
})
