<template>
  <h1>Проблемы</h1>
  <div class="filters">
    <select v-model="statusFilter" @change="load(1)">
      <option value="">Все статусы</option>
      <option value="open">open</option>
      <option value="acknowledged">acknowledged</option>
      <option value="resolved">resolved</option>
    </select>
    <select v-model="severityFilter" @change="load(1)">
      <option value="">Все severity</option>
      <option>info</option>
      <option>warning</option>
      <option>high</option>
      <option>critical</option>
    </select>
    <input v-model="hostnameFilter" placeholder="hostname" @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>Status</th>
          <th>Rule</th>
          <th>Title</th>
          <th>Действия</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="p in data?.items ?? []" :key="p.id">
          <td>
            <RouterLink :to="`/problems/${p.id}`">{{ p.id }}</RouterLink>
          </td>
          <td>{{ formatDt(p.updated_at) }}</td>
          <td>{{ p.hostname ?? "—" }}</td>
          <td :class="'sev-' + p.severity">{{ p.severity }}</td>
          <td :class="'status-' + p.status">{{ p.status }}</td>
          <td><code>{{ p.rule_id ?? "—" }}</code></td>
          <td>
            <RouterLink :to="`/problems/${p.id}`">{{ p.title }}</RouterLink>
          </td>
          <td class="actions">
            <button
              v-if="p.status === 'open'"
              type="button"
              class="secondary"
              :disabled="actingId === p.id"
              @click="doAck(p.id)"
            >
              Ack
            </button>
            <button
              v-if="p.status !== 'resolved'"
              type="button"
              :disabled="actingId === p.id"
              @click="doResolve(p.id)"
            >
              Resolve
            </button>
          </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, watch } from "vue";
import { useRoute } from "vue-router";
import { ackProblem, apiFetch, resolveProblem, type ProblemListResponse } from "../api";

const route = useRoute();

const data = ref<ProblemListResponse | null>(null);
const loading = ref(false);
const error = ref("");
const page = ref(1);
const pageSize = 50;
const statusFilter = ref("");
const severityFilter = ref("");
const hostnameFilter = ref("");
const actingId = ref<number | null>(null);

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 (statusFilter.value) params.set("status", statusFilter.value);
    if (severityFilter.value) params.set("severity", severityFilter.value);
    if (hostnameFilter.value.trim()) params.set("hostname", hostnameFilter.value.trim());
    data.value = await apiFetch<ProblemListResponse>(`/api/v1/problems?${params}`);
  } catch (e) {
    error.value = e instanceof Error ? e.message : "Ошибка загрузки";
  } finally {
    loading.value = false;
  }
}

async function doAck(id: number) {
  actingId.value = id;
  error.value = "";
  try {
    await ackProblem(id);
    await load(page.value);
  } catch (e) {
    error.value = e instanceof Error ? e.message : "Ошибка ack";
  } finally {
    actingId.value = null;
  }
}

async function doResolve(id: number) {
  actingId.value = id;
  error.value = "";
  try {
    await resolveProblem(id);
    await load(page.value);
  } catch (e) {
    error.value = e instanceof Error ? e.message : "Ошибка resolve";
  } finally {
    actingId.value = null;
  }
}

onMounted(() => {
  const status = route.query.status;
  if (typeof status === "string" && status) statusFilter.value = status;
  const severity = route.query.severity;
  if (typeof severity === "string" && severity) severityFilter.value = severity;
  const hostname = route.query.hostname;
  if (typeof hostname === "string" && hostname) hostnameFilter.value = hostname;
  load(1);
});

watch(
  () => [route.query.status, route.query.severity, route.query.hostname] as const,
  ([status, severity, hostname]) => {
    if (typeof status === "string") statusFilter.value = status;
    if (typeof severity === "string") severityFilter.value = severity;
    if (typeof hostname === "string") hostnameFilter.value = hostname;
    load(1);
  }
);
</script>
