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

const ORGAN_FIELDS = [
  { name: 'Respiratory', key: 'respiratoryScore' },
  { name: 'Coagulation', key: 'coagulationScore' },
  { name: 'Liver', key: 'liverScore' },
  { name: 'Cardiovascular', key: 'cardiovascularScore' },
  { name: 'CNS', key: 'cnsScore' },
  { name: 'Renal', key: 'renalScore' },
]

export function useSofa(encounterId) {
  const sofa = ref(null)
  const loading = ref(false)
  const error = ref(null)

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

  const total = computed(() => sofa.value?.totalScore ?? null)
  const delta = computed(() => sofa.value?.deltaFromBaseline ?? null)
  const isBaseline = computed(() => sofa.value?.isBaseline ?? false)
  const organs = computed(() => {
    if (!sofa.value) return []
    return ORGAN_FIELDS.map(({ name, key }) => ({
      name,
      score: sofa.value[key] ?? 0,
      max: 4,
    }))
  })
  const staleness = computed(() => sofa.value?.staleness ?? null)
  const hasStaleData = computed(() => {
    const s = staleness.value
    if (!s) return false
    return (s.staleComponents?.length ?? 0) > 0
      || (s.missingComponents?.length ?? 0) > 0
      || s.usedSpO2Fallback
  })

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

  return {
    sofa,
    loading,
    error,
    total,
    delta,
    isBaseline,
    organs,
    staleness,
    hasStaleData,
    fetch,
  }
}