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

const POLL_MS = 15_000

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 const useScoringStore = defineStore('scoring', () => {
  const encounterId = ref(null)
  const gcs = ref(null)
  const sofa = ref(null)
  const news2 = ref(null)
  const qsofa = ref(null)
  const loading = ref(false)
  const submittingGcs = ref(false)
  let timer = null

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

  const sofaTotal = computed(() => sofa.value?.totalScore ?? null)
  const sofaDelta = computed(() => sofa.value?.deltaFromBaseline ?? null)
  const sofaOrgans = computed(() => {
    if (!sofa.value) return []
    return [
      { name: 'Resp', score: sofa.value.respiratoryScore ?? 0 },
      { name: 'Coag', score: sofa.value.coagulationScore ?? 0 },
      { name: 'Liver', score: sofa.value.liverScore ?? 0 },
      { name: 'CV', score: sofa.value.cardiovascularScore ?? 0 },
      { name: 'CNS', score: sofa.value.cnsScore ?? 0 },
      { name: 'Renal', score: sofa.value.renalScore ?? 0 },
    ]
  })

  const news2Variant = computed(() => {
    const score = news2.value?.totalScore ?? 0
    if (score >= 7 || news2.value?.hasSingleParamThree) return 'critical'
    if (score >= 5) return 'warning'
    return 'success'
  })

  const qsofaVariant = computed(() => {
    const count = qsofa.value?.activeCriteria ?? 0
    if (count >= 2) return 'warning'
    if (count === 1) return 'warning'
    return 'success'
  })

  async function refresh() {
    if (!encounterId.value) return
    loading.value = true
    const id = encounterId.value
    try {
      const [g, s, n, q] = await Promise.all([
        clinicalApi.fetchCurrentGcs(id),
        clinicalApi.fetchCurrentSofa(id),
        clinicalApi.fetchCurrentNews2(id),
        clinicalApi.fetchCurrentQsofa(id),
      ])
      gcs.value = g
      sofa.value = s
      news2.value = n
      qsofa.value = q
    } finally {
      loading.value = false
    }
  }

  async function submitGcs(eye, verbal, motor) {
    if (!encounterId.value) return
    submittingGcs.value = true
    try {
      await clinicalApi.submitGcsObservations(encounterId.value, eye, verbal, motor)
      await refresh()
    } finally {
      submittingGcs.value = false
    }
  }

  function startPolling(id) {
    if (encounterId.value === id && timer) return
    stopPolling()
    encounterId.value = id
    refresh()
    timer = setInterval(refresh, POLL_MS)
  }

  function stopPolling() {
    if (timer) clearInterval(timer)
    timer = null
    encounterId.value = null
  }

  return {
    encounterId,
    gcs,
    sofa,
    news2,
    qsofa,
    loading,
    submittingGcs,
    gcsTotal,
    gcsComponents,
    gcsClassificationDisplay,
    sofaTotal,
    sofaDelta,
    sofaOrgans,
    news2Variant,
    qsofaVariant,
    refresh,
    submitGcs,
    startPolling,
    stopPolling,
  }
})