<script setup>
import { computed, onMounted, onBeforeUnmount } from 'vue'
import { storeToRefs } from 'pinia'
import { useSepsisStore } from '@/stores/sepsis'
import { usePolling } from '@/composables/usePolling'
import SepsisBundleTable from '@/components/sepsis/SepsisBundleTable.vue'
import Skeleton from '@/components/ui/Skeleton.vue'
import EmptyState from '@/components/ui/EmptyState.vue'
import Badge from '@/components/ui/Badge.vue'

const sepsisStore = useSepsisStore()
const { sortedBundles, loading, error, summary, now } = storeToRefs(sepsisStore)

usePolling(() => sepsisStore.loadBundles(), 10_000)

let countdownTimer = null
onMounted(() => {
  sepsisStore.loadBundles()
  countdownTimer = setInterval(() => sepsisStore.tick(), 1000)
})
onBeforeUnmount(() => {
  if (countdownTimer) clearInterval(countdownTimer)
})

const summaryLine = computed(() => {
  const total = sortedBundles.value.length
  if (total === 0) return 'No active sepsis bundles'
  const { on_track: onTrack, at_risk: atRisk, overdue } = summary.value
  return `${total} active bundle${total === 1 ? '' : 's'} — ${onTrack} on track, ${atRisk} at risk, ${overdue} overdue`
})
</script>

<template>
  <div>
    <div class="mb-4 flex flex-wrap items-center justify-between gap-4">
      <div>
        <h1 class="text-xl font-bold dark:text-white">Sepsis Bundle Board</h1>
        <p class="mt-2 text-sm text-gray-600 dark:text-gray-400">{{ summaryLine }}</p>
      </div>
      <div class="flex flex-wrap gap-2">
        <Badge v-if="summary.overdue > 0" variant="critical">{{ summary.overdue }} overdue</Badge>
        <Badge v-if="summary.at_risk > 0" variant="warning">{{ summary.at_risk }} at risk</Badge>
      </div>
    </div>

    <p v-if="error" class="mb-4 text-sm text-red-600 dark:text-red-400">{{ error }}</p>

    <Skeleton v-if="loading && sortedBundles.length === 0" :rows="4" />
    <EmptyState v-else-if="sortedBundles.length === 0" message="No active sepsis bundles" />
    <SepsisBundleTable
      v-else
      :bundles="sortedBundles"
      :now="now"
    />
  </div>
</template>
