import { ref, computed, unref, watch } from 'vue'
import * as clinicalApi from '@/api/clinical'

function gcsClassification(total) {
  if (total <= 8) return { label: 'Severe', variant: 'critical' }
  if (total <= 12) return { label: 'Moderate', variant: 'warning' }
  return { label: 'Mild', variant: 'success' }
}

export function useGcs(encounterId) {
  const gcs = ref(null)
  const loading = ref(false)
  const submitting = ref(false)
  const error = ref(null)

  async function fetch() {
    const id = unref(encounterId)
    if (!id) return
    loading.value = true
    error.value = null
    try {
      gcs.value = await clinicalApi.fetchCurrentGcs(id)
    } catch (e) {
      gcs.value = null
      error.value = e.message
    } finally {
      loading.value = false
    }
  }

  async function submit(eye, verbal, motor) {
    const id = unref(encounterId)
    if (!id) return

    const previous = gcs.value
    const optimisticTotal = eye + verbal + motor
    gcs.value = {
      eyeScore: eye,
      verbalScore: verbal,
      motorScore: motor,
      totalScore: optimisticTotal,
      classification: gcsClassification(optimisticTotal).label.toUpperCase(),
      calculatedAt: new Date().toISOString(),
    }

    submitting.value = true
    error.value = null
    try {
      await clinicalApi.submitGcsObservations(id, eye, verbal, motor)
      await fetch()
    } catch (e) {
      gcs.value = previous
      error.value = e.message
      throw e
    } finally {
      submitting.value = false
    }
  }

  const total = computed(() => gcs.value?.totalScore ?? null)
  const components = computed(() => {
    if (!gcs.value) return null
    return {
      eye: gcs.value.eyeScore,
      verbal: gcs.value.verbalScore,
      motor: gcs.value.motorScore,
    }
  })
  const classification = computed(() => {
    if (total.value == null) return null
    return gcsClassification(total.value)
  })

  watch(() => unref(encounterId), fetch, { immediate: true })

  return {
    gcs,
    loading,
    submitting,
    error,
    total,
    components,
    classification,
    fetch,
    submit,
  }
}