<template>
  <h1>Проблемы</h1>
  <div class="filters">
    <select v-model="statusFilter" @change="applyFilters">
      <option value="">Все статусы</option>
      <option value="open">open</option>
      <option value="acknowledged">acknowledged</option>
      <option value="resolved">resolved</option>
    </select>
    <select v-model="severityFilter" @change="applyFilters">
      <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="applyFilters" />
    <button type="button" @click="applyFilters">Применить</button>
  </div>
  <p v-if="timeFilterHint" class="muted">{{ timeFilterHint }}</p>
  <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>Имя сервера</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>{{ formatServerName(p.display_name) }}</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">
            <div class="actions-inner">
              <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>
              <span v-if="p.status === 'resolved'" class="actions-muted">Закрыта</span>
            </div>
          </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 { computed, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ackProblem, apiFetch, resolveProblem, type ProblemListResponse } from "../api";
import { formatServerName } from "../utils/hostDisplay";

const route = useRoute();
const router = useRouter();

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 createdWithinHours = ref("");
const resolvedWithinHours = ref("");
const actingId = ref<number | null>(null);

const timeFilterHint = computed(() => {
  if (createdWithinHours.value) {
    return `Показаны проблемы, созданные за последние ${createdWithinHours.value} ч (любой статус).`;
  }
  if (resolvedWithinHours.value) {
    return `Показаны проблемы, закрытые за последние ${resolvedWithinHours.value} ч.`;
  }
  return "";
});

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

function buildProblemsQuery(): Record<string, string> {
  const q: Record<string, string> = {};
  if (statusFilter.value && !resolvedWithinHours.value) q.status = statusFilter.value;
  if (severityFilter.value) q.severity = severityFilter.value;
  if (hostnameFilter.value.trim()) q.hostname = hostnameFilter.value.trim();
  if (createdWithinHours.value) q.created_within_hours = createdWithinHours.value;
  if (resolvedWithinHours.value) q.resolved_within_hours = resolvedWithinHours.value;
  return q;
}

function applyFilters() {
  if (resolvedWithinHours.value) createdWithinHours.value = "";
  else if (createdWithinHours.value) resolvedWithinHours.value = "";
  void router.replace({ path: "/problems", query: buildProblemsQuery() });
  void load(1);
}

function syncFromRoute() {
  const status = route.query.status;
  statusFilter.value = typeof status === "string" ? status : "";
  const severity = route.query.severity;
  severityFilter.value = typeof severity === "string" ? severity : "";
  const hostname = route.query.hostname;
  hostnameFilter.value = typeof hostname === "string" ? hostname : "";
  const created = route.query.created_within_hours;
  createdWithinHours.value = typeof created === "string" ? created : "";
  const resolved = route.query.resolved_within_hours;
  resolvedWithinHours.value = typeof resolved === "string" ? resolved : "";
  if (resolvedWithinHours.value) statusFilter.value = "resolved";
}

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(() => {
  syncFromRoute();
  load(1);
});

watch(
  () =>
    [
      route.query.status,
      route.query.severity,
      route.query.hostname,
      route.query.created_within_hours,
      route.query.resolved_within_hours,
    ] as const,
  () => {
    syncFromRoute();
    load(1);
  },
);
</script>
