<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import Card from '@/components/ui/Card.vue'
import Badge from '@/components/ui/Badge.vue'
import { bundleElementLabel, bundleTriggerLabel } from '@/api/normalize'

const props = defineProps({
  bundle: { type: Object, default: null },
  qsofa: { type: Object, default: null },
  sofa: { type: Object, default: null },
})

const now = ref(Date.now())
let timer = null

onMounted(() => {
  timer = setInterval(() => {
    now.value = Date.now()
  }, 1000)
})

onBeforeUnmount(() => {
  if (timer) clearInterval(timer)
})

const showQsofaScreenMessage = computed(() => {
  if (props.bundle) return false
  return (props.qsofa?.activeCriteria ?? 0) >= 2
})

const triggerLabel = computed(() =>
  bundleTriggerLabel(props.bundle?.triggeringAlertType),
)

const remainingMs = computed(() => {
  if (!props.bundle?.deadlineAt) return 0
  const deadline = new Date(props.bundle.deadlineAt).getTime()
  return Math.max(0, deadline - now.value)
})

const countdown = computed(() => {
  const ms = remainingMs.value
  const mins = Math.floor(ms / 60_000)
  const secs = Math.floor((ms % 60_000) / 1000)
  return `${mins}:${secs.toString().padStart(2, '0')}`
})

const complianceVariant = computed(() => {
  const status = props.bundle?.complianceStatus
  if (status === 'Compliant') return 'success'
  if (status === 'NonCompliant') return 'critical'
  return 'warning'
})

function elementComplete(element) {
  return element.status === 'Completed'
}
</script>

<template>
  <Card>
    <template #header>
      <div class="mb-4 flex flex-wrap items-center justify-between gap-4">
        <h2 class="text-sm font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">
          Sepsis Bundle
        </h2>
        <Badge v-if="bundle" :variant="complianceVariant">{{ bundle.complianceStatus }}</Badge>
      </div>
    </template>

    <div
      v-if="showQsofaScreenMessage"
      class="mb-4 rounded-lg bg-amber-50 px-4 py-2 text-sm text-amber-800 dark:bg-amber-900/20 dark:text-amber-200"
    >
      qSOFA screen positive — order SOFA labs to evaluate organ dysfunction.
    </div>

    <div v-if="sofa?.totalScore != null" class="mb-4 flex flex-wrap items-center gap-2 text-sm dark:text-gray-300">
      <span>Current SOFA:</span>
      <Badge variant="info" size="xs">{{ sofa.totalScore }}/24</Badge>
      <Badge
        v-if="sofa.deltaFromBaseline != null && sofa.deltaFromBaseline >= 2"
        variant="critical"
        size="xs"
      >
        Δ +{{ sofa.deltaFromBaseline }}
      </Badge>
    </div>

    <template v-if="bundle">
      <p class="mb-4 text-xs text-gray-500 dark:text-gray-400">
        Triggered by {{ triggerLabel }}
      </p>

      <div class="mb-4 flex flex-wrap items-center justify-between gap-4 rounded-lg bg-gray-50 p-4 dark:bg-gray-800">
        <span class="text-sm text-gray-600 dark:text-gray-300">Time to deadline</span>
        <span
          class="font-mono text-lg font-semibold"
          :class="remainingMs === 0 ? 'text-red-600 dark:text-red-400' : 'text-gray-900 dark:text-white'"
        >
          {{ countdown }}
        </span>
      </div>

      <ul class="space-y-2">
        <li
          v-for="element in bundle.elements"
          :key="element.id"
          class="flex flex-wrap items-center gap-4 rounded-lg border border-gray-200 p-4 dark:border-gray-700"
        >
          <span
            class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-xs"
            :class="elementComplete(element)
              ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300'
              : 'bg-gray-100 text-gray-400 dark:bg-gray-800 dark:text-gray-500'"
          >
            {{ elementComplete(element) ? '✓' : '○' }}
          </span>
          <span
            class="min-w-0 flex-1 text-sm"
            :class="elementComplete(element)
              ? 'text-gray-500 line-through dark:text-gray-400'
              : 'text-gray-900 dark:text-white'"
          >
            {{ bundleElementLabel(element.elementType) }}
          </span>
        </li>
      </ul>
    </template>

    <p v-else class="text-sm text-gray-500 dark:text-gray-400">
      No active sepsis bundle for this encounter.
    </p>
  </Card>
</template>