<script setup>
import { computed } from 'vue'
import { useSofa } from '@/composables/useSofa'
import Badge from '@/components/ui/Badge.vue'
import Card from '@/components/ui/Card.vue'

const props = defineProps({
  encounterId: { type: String, required: true },
})

const encounterIdRef = computed(() => props.encounterId)
const { total, delta, organs, hasStaleData, staleness, loading, fetch } = useSofa(encounterIdRef)

function organVariant(score) {
  if (score === 0) return 'success'
  if (score <= 2) return 'warning'
  return 'critical'
}
</script>

<template>
  <Card>
    <div class="space-y-4">
      <div class="flex flex-wrap items-center justify-between gap-4">
        <h3 class="text-sm font-semibold dark:text-white">SOFA Score</h3>
        <div v-if="loading" class="text-sm text-gray-400 dark:text-gray-500">Loading…</div>
        <div v-else-if="total !== null" class="flex flex-wrap items-center gap-2">
          <span class="text-2xl font-bold dark:text-white">{{ total }}/24</span>
          <Badge v-if="delta !== null && delta >= 2" variant="critical" size="xs">
            +{{ delta }} from baseline
          </Badge>
          <Badge v-else-if="delta !== null && delta === 1" variant="warning" size="xs">
            +{{ delta }} from baseline
          </Badge>
        </div>
        <span v-else class="text-sm text-gray-400 dark:text-gray-500">Labs pending</span>
      </div>

      <div v-if="organs.length" class="grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-6">
        <div
          v-for="organ in organs"
          :key="organ.name"
          class="rounded-lg bg-gray-50 p-4 text-center dark:bg-gray-800"
        >
          <div class="text-xs text-gray-500 dark:text-gray-400">{{ organ.name }}</div>
          <div class="mt-2">
            <Badge :variant="organVariant(organ.score)" size="sm">
              {{ organ.score }}/{{ organ.max }}
            </Badge>
          </div>
        </div>
      </div>

      <div
        v-if="hasStaleData"
        class="rounded bg-amber-50 px-4 py-2 text-xs text-amber-700 dark:bg-amber-900/20 dark:text-amber-300"
      >
        <span v-if="staleness?.missingComponents?.length">
          Missing: {{ staleness.missingComponents.join(', ') }}.
        </span>
        <span v-if="staleness?.staleComponents?.length">
          Stale: {{ staleness.staleComponents.join(', ') }}.
        </span>
        <span v-if="staleness?.usedSpO2Fallback">
          Using SpO₂/FiO₂ proxy (no arterial blood gas).
        </span>
      </div>

      <button
        type="button"
        class="text-xs text-blue-600 hover:underline dark:text-blue-400"
        @click="fetch"
      >
        Refresh SOFA
      </button>
    </div>
  </Card>
</template>