<template>
  <h1>События</h1>
  <div class="filters">
    <input v-model="q" placeholder="Поиск в summary/title" @keyup.enter="load(1)" />
    <select v-model="severity" @change="load(1)">
      <option value="">Все severity</option>
      <option>info</option>
      <option>warning</option>
      <option>high</option>
      <option>critical</option>
    </select>
    <input v-model="typeFilter" placeholder="type" @keyup.enter="load(1)" />
    <button type="button" @click="load(1)">Применить</button>
  </div>
  <p v-if="error" class="error">{{ error }}</p>
  <p v-else-if="loading">Загрузка…</p>
  <template v-else>
    <p>Всего: {{ data?.total ?? 0 }}</p>
    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>Время</th>
          <th>Хост</th>
          <th>Severity</th>
          <th>Type</th>
          <th>Title</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="e in data?.items ?? []" :key="e.id">
          <td>
            <RouterLink :to="`/events/${e.id}`">{{ e.id }}</RouterLink>
          </td>
          <td>{{ formatDt(e.occurred_at) }}</td>
          <td>{{ e.hostname }}</td>
          <td :class="'sev-' + e.severity">{{ e.severity }}</td>
          <td><code>{{ e.type }}</code></td>
          <td>{{ e.title }}</td>
        </tr>
      </tbody>
    </table>
    <div class="filters" style="margin-top: 1rem">
      <button type="button" class="secondary" :disabled="page <= 1" @click="load(page - 1)">Назад</button>
      <span>Стр. {{ page }}</span>
      <button
        type="button"
        class="secondary"
        :disabled="!data || page * pageSize >= data.total"
        @click="load(page + 1)"
      >
        Вперёд
      </button>
    </div>
  </template>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { apiFetch, type EventListResponse } from "../api";

const data = ref<EventListResponse | null>(null);
const loading = ref(false);
const error = ref("");
const page = ref(1);
const pageSize = 50;
const q = ref("");
const severity = ref("");
const typeFilter = ref("");

function formatDt(iso: string) {
  return new Date(iso).toLocaleString("ru-RU");
}

async function load(p: number) {
  page.value = p;
  loading.value = true;
  error.value = "";
  try {
    const params = new URLSearchParams({
      page: String(page.value),
      page_size: String(pageSize),
    });
    if (severity.value) params.set("severity", severity.value);
    if (typeFilter.value) params.set("type", typeFilter.value);
    if (q.value.trim()) params.set("q", q.value.trim());
    data.value = await apiFetch<EventListResponse>(`/api/v1/events?${params}`);
  } catch (e) {
    error.value = e instanceof Error ? e.message : "Ошибка загрузки";
  } finally {
    loading.value = false;
  }
}

onMounted(() => load(1));
</script>
