<script setup>
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'
import { useDepartmentsStore } from '@/stores/departments'
import { usePolling } from '@/composables/usePolling'
import DepartmentCard from '@/components/departments/DepartmentCard.vue'
import Card from '@/components/ui/Card.vue'
import Badge from '@/components/ui/Badge.vue'
import Skeleton from '@/components/ui/Skeleton.vue'

const router = useRouter()
const departmentsStore = useDepartmentsStore()
const { departments, totals, loading, error } = storeToRefs(departmentsStore)

usePolling(() => departmentsStore.load(), 10_000)

function onSelectDepartment(filterValue) {
  router.push({ name: 'WardDashboard', query: { department: filterValue } })
}
</script>

<template>
  <div class="space-y-8">
    <div class="flex flex-wrap items-center justify-between gap-4">
      <div>
        <h1 class="text-xl font-bold dark:text-white">Department Overview</h1>
        <p class="mt-2 text-sm text-gray-600 dark:text-gray-400">
          Unit-level snapshot across active patients, acuity, alerts, and sepsis bundles.
        </p>
      </div>
      <div class="flex flex-wrap gap-2">
        <Badge v-if="totals.criticalCount > 0" variant="critical">
          {{ totals.criticalCount }} critical
        </Badge>
        <Badge v-if="totals.openAlertCount > 0" variant="warning">
          {{ totals.openAlertCount }} open alerts
        </Badge>
      </div>
    </div>

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

    <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
      <Card>
        <div class="text-center">
          <div class="text-3xl font-bold dark:text-white">{{ totals.patientCount }}</div>
          <div class="text-sm text-gray-500 dark:text-gray-400">Active patients</div>
        </div>
      </Card>
      <Card>
        <div class="text-center">
          <div class="text-3xl font-bold text-red-600">{{ totals.criticalCount }}</div>
          <div class="text-sm text-gray-500 dark:text-gray-400">Critical (NEWS2 ≥ 7)</div>
        </div>
      </Card>
      <Card>
        <div class="text-center">
          <div class="text-3xl font-bold text-amber-600">{{ totals.openAlertCount }}</div>
          <div class="text-sm text-gray-500 dark:text-gray-400">Open alerts</div>
        </div>
      </Card>
      <Card>
        <div class="text-center">
          <div class="text-3xl font-bold text-blue-600">{{ totals.activeBundleCount }}</div>
          <div class="text-sm text-gray-500 dark:text-gray-400">Active sepsis bundles</div>
        </div>
      </Card>
    </div>

    <Skeleton v-if="loading && departments.length === 0" :rows="3" />
    <div v-else class="grid grid-cols-1 gap-4 xl:grid-cols-3">
      <DepartmentCard
        v-for="department in departments"
        :key="department.key"
        :department="department"
        @select="onSelectDepartment"
      />
    </div>
  </div>
</template>
