<script setup>
import { ref, watch, onMounted, onBeforeUnmount } from 'vue'
import { storeToRefs } from 'pinia'
import { useAlertStore } from '@/stores/alerts'
import { alertStatusToApiFilter } from '@/api/normalize'
import AlertCard from '@/components/alerts/AlertCard.vue'
import AlertFilters from '@/components/alerts/AlertFilters.vue'
import AcknowledgeModal from '@/components/alerts/AcknowledgeModal.vue'
import Skeleton from '@/components/ui/Skeleton.vue'
import EmptyState from '@/components/ui/EmptyState.vue'

const alertStore = useAlertStore()
const { alerts, loading } = storeToRefs(alertStore)

const activeFilter = ref('OPEN')
const confirmingAlert = ref(null)

watch(activeFilter, (status) => {
  alertStore.loadGlobalAlerts(alertStatusToApiFilter(status))
}, { immediate: true })

let pollTimer = null
onMounted(() => {
  pollTimer = setInterval(() => {
    if (confirmingAlert.value) return
    alertStore.loadGlobalAlerts(alertStatusToApiFilter(activeFilter.value))
  }, 10_000)
})
onBeforeUnmount(() => {
  if (pollTimer) clearInterval(pollTimer)
})

async function handleAcknowledge(note) {
  if (!confirmingAlert.value) return
  await alertStore.acknowledge(confirmingAlert.value.id, note)
  confirmingAlert.value = null
  alertStore.loadGlobalAlerts(alertStatusToApiFilter(activeFilter.value))
}

async function handleResolve(alertId) {
  await alertStore.resolve(alertId)
  alertStore.loadGlobalAlerts(alertStatusToApiFilter(activeFilter.value))
}
</script>

<template>
  <div>
    <h1 class="mb-4 text-xl font-bold dark:text-white">Alert Center</h1>

    <AlertFilters v-model="activeFilter" />

    <Skeleton v-if="loading && alerts.length === 0" class="mt-4" :rows="4" />
    <EmptyState v-else-if="alerts.length === 0" class="mt-4" message="No alerts for this status" />
    <div v-else class="mt-4 space-y-4">
      <AlertCard
        v-for="alert in alerts"
        :key="alert.id"
        :alert="alert"
        @acknowledge="confirmingAlert = alert"
        @resolve="handleResolve(alert.id)"
      />
    </div>

    <AcknowledgeModal
      :open="!!confirmingAlert"
      :alert="confirmingAlert"
      @confirm="handleAcknowledge"
      @close="confirmingAlert = null"
    />
  </div>
</template>