<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { systemAPI } from "@/api";
import BaseDialog from "@/components/common/BaseDialog.vue";
import DataTable from "@/components/common/DataTable.vue";
import type { DataTableColumn } from "@/components/common/DataTable.vue";
import EmptyState from "@/components/common/EmptyState.vue";
import LoadingState from "@/components/common/LoadingState.vue";
import PageHeader from "@/components/common/PageHeader.vue";
import Pagination from "@/components/common/Pagination.vue";
import TablePageLayout from "@/components/layout/TablePageLayout.vue";
import { useTableLoader } from "@/composables/useTableLoader";
import type { GateDiagnosticRow, GateDiagnosticsResponse } from "@/types";

const columns: DataTableColumn[] = [
  { key: "category", label: "类别" },
  { key: "check", label: "检查项" },
  { key: "status", label: "状态" },
  { key: "owner", label: "归因对象" },
  { key: "detail", label: "关键细节" },
  { key: "actions", label: "下钻", align: "right" }
];

const payload = ref<GateDiagnosticsResponse | null>(null);
const query = ref("");
const statusFilter = ref("all");
const selectedRow = ref<GateDiagnosticRow | null>(null);
const page = ref(1);
const pageSize = 8;

const table = useTableLoader<GateDiagnosticRow>(async () => {
  const response = await systemAPI.gateDiagnostics();
  if (!response.ok) throw response;
  payload.value = response.data;
  return response.data?.rows ?? [];
});

const rows = computed(() => table.rows.value);
const statusCounts = computed(() => ({
  failed: rows.value.filter((row) => row.statusKey === "failed").length,
  blocked: rows.value.filter((row) => row.statusKey === "blocked").length,
  pending: rows.value.filter((row) => row.statusKey === "pending").length,
  pass: rows.value.filter((row) => row.statusKey === "pass").length
}));
const filteredRows = computed(() => {
  const needle = query.value.trim().toLowerCase();
  return rows.value.filter((row) => {
    if (statusFilter.value !== "all" && row.statusKey !== statusFilter.value) return false;
    if (!needle) return true;
    return [row.category, row.check, row.status, row.owner, row.detail, row.next, evidenceList(row).join(" ")]
      .join(" ")
      .toLowerCase()
      .includes(needle);
  });
});
const pageRows = computed(() => filteredRows.value.slice((page.value - 1) * pageSize, page.value * pageSize));

watch([query, statusFilter], () => { page.value = 1; });
onMounted(() => void table.reload());

function rowKey(row: GateDiagnosticRow): string {
  return `${row.category ?? "category"}:${row.check ?? "check"}`;
}

function evidenceList(row: GateDiagnosticRow): string[] {
  if (Array.isArray(row.evidence)) return row.evidence.map(String);
  if (typeof row.evidence === "string" && row.evidence.trim()) return [row.evidence];
  return [];
}

function statusLabel(row: GateDiagnosticRow): string {
  return row.status ?? row.statusKey ?? "unknown";
}

function displayDate(value?: string): string {
  if (!value) return "-";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return value;
  return date.toLocaleString("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" });
}
</script>

<template>
  <section class="route-stack system-page gate-page">
    <PageHeader eyebrow="System" title="内部复核" description="Gate diagnostics 直接读取 /v1/diagnostics/gate 的 live 聚合结果，用表格、筛选和 drill-down 展示失败归因。" />
    <LoadingState v-if="table.loading.value && !rows.length" />
    <section v-else-if="table.error.value" class="data-panel">
      <EmptyState title="Gate diagnostics 加载失败" :description="table.error.value" :api-error="table.apiError.value" :diagnostic="table.diagnostic.value" action-label="重试" @action="table.reload" />
    </section>
    <template v-else>
      <section class="system-summary-grid" aria-label="Gate live aggregation">
        <article class="metric-card"><span>Status</span><strong>{{ payload?.status || 'unknown' }}</strong><small>{{ payload?.sourceKind || '-' }}</small></article>
        <article class="metric-card"><span>Rows</span><strong>{{ rows.length }}</strong><small>{{ payload?.contractVersion || '-' }}</small></article>
        <article class="metric-card"><span>Blocked</span><strong>{{ statusCounts.blocked + statusCounts.failed }}</strong><small>failed {{ statusCounts.failed }} / blocked {{ statusCounts.blocked }}</small></article>
        <article class="metric-card"><span>Observed</span><strong>{{ displayDate(payload?.observedAt) }}</strong><small>liveBackend={{ payload?.liveBackend ? 'true' : 'false' }}</small></article>
      </section>
      <TablePageLayout title="Diagnostics" subtitle="live aggregation / filter / failure drill-down">
        <template #actions>
          <button class="table-action" type="button" :disabled="table.loading.value" @click="table.reload">刷新</button>
        </template>
        <template #filters>
          <div class="system-filter-bar">
            <label><span>状态</span><select v-model="statusFilter"><option value="all">全部</option><option value="failed">failed</option><option value="blocked">blocked</option><option value="pending">pending</option><option value="pass">pass</option></select></label>
            <label><span>搜索</span><input v-model="query" type="search" placeholder="类别 / 检查项 / blocker / trace"></label>
          </div>
        </template>
        <DataTable :columns="columns" :rows="pageRows" :row-key="rowKey" empty-text="当前筛选没有 Gate 诊断行。">
          <template #cell-category="{ row }"><strong>{{ (row as GateDiagnosticRow).category || '-' }}</strong></template>
          <template #cell-check="{ row }"><span>{{ (row as GateDiagnosticRow).check || '-' }}</span><small>{{ displayDate((row as GateDiagnosticRow).updatedAt) }}</small></template>
          <template #cell-status="{ row }"><span class="status-pill" :data-status="(row as GateDiagnosticRow).statusKey || 'pending'">{{ statusLabel(row as GateDiagnosticRow) }}</span></template>
          <template #cell-owner="{ row }"><code>{{ (row as GateDiagnosticRow).owner || '-' }}</code></template>
          <template #cell-detail="{ row }"><span class="system-row-detail">{{ (row as GateDiagnosticRow).detail || '-' }}</span></template>
          <template #cell-actions="{ row }"><button class="table-action" type="button" @click="selectedRow = row as GateDiagnosticRow">Detail</button></template>
        </DataTable>
        <template #pagination><Pagination v-model:page="page" :page-size="pageSize" :total="filteredRows.length" /></template>
      </TablePageLayout>
      <BaseDialog :open="selectedRow !== null" title="Gate failure drill-down" :description="selectedRow?.check || ''" wide @close="selectedRow = null">
        <dl v-if="selectedRow" class="field-grid">
          <div><dt>category</dt><dd>{{ selectedRow.category || '-' }}</dd></div>
          <div><dt>status</dt><dd>{{ statusLabel(selectedRow) }}</dd></div>
          <div><dt>owner</dt><dd>{{ selectedRow.owner || '-' }}</dd></div>
          <div><dt>updated</dt><dd>{{ displayDate(selectedRow.updatedAt) }}</dd></div>
        </dl>
        <section v-if="selectedRow" class="system-drilldown">
          <h3>关键细节</h3>
          <p>{{ selectedRow.detail || '-' }}</p>
          <h3>证据 / trace</h3>
          <ul><li v-for="item in evidenceList(selectedRow)" :key="item"><code>{{ item }}</code></li></ul>
          <h3>下一步</h3>
          <p>{{ selectedRow.next || '-' }}</p>
        </section>
      </BaseDialog>
    </template>
  </section>
</template>
