<script setup>
import { storeToRefs } from 'pinia'
import { useWardStore } from '@/stores/ward'
import { usePolling } from '@/composables/usePolling'
import WardTable from '@/components/ward/WardTable.vue'
import Skeleton from '@/components/ui/Skeleton.vue'
import EmptyState from '@/components/ui/EmptyState.vue'
import Badge from '@/components/ui/Badge.vue'

const wardStore = useWardStore()
const { sortedByRisk, loading, error, criticalCount, department } = storeToRefs(wardStore)

usePolling(() => wardStore.loadEncounters(), 10_000)

const departments = [
  { value: '', label: 'All departments' },
  { value: 'ICU', label: 'ICU' },
  { value: 'GENERAL_MEDICINE', label: 'General Medicine' },
  { value: 'SURGERY', label: 'Surgery' },
]

function onDepartmentChange(event) {
  wardStore.setDepartment(event.target.value || null)
}
</script>

<template>
  <div>
    <div class="mb-4 flex flex-wrap items-center justify-between gap-4">
      <h1 class="text-xl font-bold dark:text-white">Virtual Ward</h1>
      <Badge v-if="criticalCount > 0" variant="critical">
        {{ criticalCount }} critical
      </Badge>
    </div>

    <label class="mb-4 block sm:hidden">
      <span class="mb-2 block text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400">
        Department
      </span>
      <select
        :value="department ?? ''"
        class="w-full rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm text-gray-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200"
        @change="onDepartmentChange"
      >
        <option v-for="dept in departments" :key="dept.value" :value="dept.value">
          {{ dept.label }}
        </option>
      </select>
    </label>

    <Skeleton v-if="loading && sortedByRisk.length === 0" :rows="5" />
    <EmptyState v-else-if="sortedByRisk.length === 0" message="No active patients" />
    <WardTable v-else :patients="sortedByRisk" />
  </div>
</template>