<template>
  <div class="system-monitor">
    <div class="system-monitor__content">
      <div v-if="activeTab === 'monitor'" class="system-monitor__monitor">
        <div v-if="loading" class="system-monitor__loading">
          <a-spin size="small" />
          <span>加载监控数据中...</span>
        </div>

        <div v-else-if="error" class="system-monitor__error">
          <WarningOutlined />
          <span>{{ error }}</span>
        </div>

        <div v-else class="system-monitor__body">
        <div class="system-monitor__section-title">系统概览</div>
        <div class="system-monitor__metrics">
          <div class="system-monitor__metric">
            <div class="system-monitor__metric-label">服务状态</div>
            <div class="system-monitor__metric-value" :class="`status-${health.status}`">
              {{ statusText }}
            </div>
            <div class="system-monitor__metric-delta">
              v{{ health.version || '—' }}
            </div>
          </div>
          <div class="system-monitor__metric">
            <div class="system-monitor__metric-label">任务总数</div>
            <div class="system-monitor__metric-value">{{ metrics.tasks.total_tasks }}</div>
            <div class="system-monitor__metric-delta">
              完成 {{ metrics.tasks.completed_tasks }} / 失败 {{ metrics.tasks.failed_tasks }}
            </div>
          </div>
          <div class="system-monitor__metric">
            <div class="system-monitor__metric-label">在线 Agent</div>
            <div class="system-monitor__metric-value">{{ metrics.agents.total_agents }}</div>
            <div class="system-monitor__metric-delta">已注册技能 {{ metrics.skills.total_skills }}</div>
          </div>
          <div class="system-monitor__metric">
            <div class="system-monitor__metric-label">待处理任务</div>
            <div class="system-monitor__metric-value">{{ metrics.tasks.pending_tasks }}</div>
            <div class="system-monitor__metric-delta" :class="metrics.tasks.pending_tasks > 0 ? 'down' : 'up'">
              {{ metrics.tasks.pending_tasks > 0 ? '队列中有任务' : '队列空闲' }}
            </div>
          </div>
        </div>

        <div class="system-monitor__split">
          <div class="system-monitor__column">
            <div class="system-monitor__section-title">服务状态</div>
            <div class="system-monitor__services">
              <div
                v-for="s in serviceList"
                :key="s.name"
                class="system-monitor__service"
              >
                <span class="system-monitor__service-dot" :class="s.ok ? 'ok' : 'error'" />
                <span class="system-monitor__service-name">{{ s.name }}</span>
                <span class="system-monitor__service-status">{{ s.ok ? '正常' : '异常' }}</span>
                <span class="system-monitor__service-time">{{ s.detail }}</span>
              </div>
            </div>
          </div>

          <div class="system-monitor__column">
            <div class="system-monitor__section-title">错误趋势（7天）</div>
            <div class="system-monitor__chart-placeholder">
              <LineChartOutlined />
              <span>历史趋势图表需接入日志/指标存储</span>
            </div>
          </div>
        </div>
        </div>
      </div>

      <SkillsTab v-else-if="activeTab === 'engines'" category="agent_template" />
      <SkillsTab v-else-if="activeTab === 'skills'" category="business_skill" />
      <DocumentsTab v-else-if="activeTab === 'documents'" />
      <CalendarTab v-else-if="activeTab === 'calendar'" />
      <SystemTab v-else-if="activeTab === 'system'" />
      <KnowledgeTab v-else-if="activeTab === 'knowledge'" />
      <!-- ponytail: v-else fallback catches unknown activeTab values (corrupted state / future tabs) -->
      <div v-else class="system-monitor__unknown-tab">未知标签页: {{ activeTab }}</div>
    </div>

    <nav class="system-monitor__tabs" role="tablist" aria-label="右侧功能导航" @keydown="onTabKeydown">
      <a-tooltip
        v-for="tab in tabs"
        :key="tab.key"
        :title="tab.label"
        placement="left"
      >
        <button
          type="button"
          class="system-monitor__tab"
          role="tab"
          :aria-selected="activeTab === tab.key"
          :aria-label="tab.label"
          :class="{ 'system-monitor__tab--active': activeTab === tab.key }"
          @click="activeTab = tab.key"
        >
          <component :is="tab.icon" class="system-monitor__tab-icon" />
        </button>
      </a-tooltip>
    </nav>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import type { Component } from 'vue'
import { Spin as ASpin } from 'ant-design-vue'
import {
  DashboardOutlined,
  AppstoreOutlined,
  ThunderboltOutlined,
  SettingOutlined,
  BookOutlined,
  CalendarOutlined,
  FolderOpenOutlined,
  WarningOutlined,
  LineChartOutlined,
} from '@ant-design/icons-vue'
import {
  getHealth,
  getMetrics,
  type IHealthCheck,
  type IMetricsData,
} from '@/api/system'
import SkillsTab from './tabs/SkillsTab.vue'
import SystemTab from './tabs/SystemTab.vue'
import KnowledgeTab from './tabs/KnowledgeTab.vue'
import CalendarTab from './tabs/CalendarTab.vue'
import DocumentsTab from './tabs/DocumentsTab.vue'

interface Tab {
  key: string
  label: string
  icon: Component
}

const tabs: Tab[] = [
  { key: 'monitor', label: '监控', icon: DashboardOutlined as Component },
  { key: 'engines', label: '引擎', icon: ThunderboltOutlined as Component },
  { key: 'skills', label: '技能', icon: AppstoreOutlined as Component },
  { key: 'documents', label: '文档', icon: FolderOpenOutlined as Component },
  { key: 'calendar', label: '日程', icon: CalendarOutlined as Component },
  { key: 'system', label: '系统', icon: SettingOutlined as Component },
  { key: 'knowledge', label: '知识库', icon: BookOutlined as Component },
]

const activeTab = ref('monitor')
const loading = ref(false)
const error = ref('')
// ponytail: 首次加载标志 — 后续定时刷新静默更新数据，不切换 loading/error DOM，
// 避免每 10 秒整个面板 reload 到 spinner 再回来的视觉闪烁。升级路径：WebSocket 推送。
const initialLoading = ref(true)

// ponytail: WAI-ARIA tablist keyboard navigation — ArrowUp/Down move between
// tabs, Home/End jump to first/last. Required for keyboard-only users.
function onTabKeydown(e: KeyboardEvent): void {
  const keys = ['ArrowUp', 'ArrowDown', 'Home', 'End']
  if (!keys.includes(e.key)) return
  e.preventDefault()
  const idx = tabs.findIndex((t) => t.key === activeTab.value)
  if (e.key === 'ArrowUp') activeTab.value = tabs[(idx - 1 + tabs.length) % tabs.length].key
  else if (e.key === 'ArrowDown') activeTab.value = tabs[(idx + 1) % tabs.length].key
  else if (e.key === 'Home') activeTab.value = tabs[0].key
  else if (e.key === 'End') activeTab.value = tabs[tabs.length - 1].key
}
const health = ref<IHealthCheck>({ status: 'unknown', version: '', checks: {} })
const metrics = ref<IMetricsData>({
  tasks: { total_tasks: 0, completed_tasks: 0, failed_tasks: 0, pending_tasks: 0 },
  agents: { total_agents: 0 },
  skills: { total_skills: 0 },
  version: '',
})
const statusText = computed(() => {
  const map: Record<string, string> = {
    healthy: '健康',
    degraded: '降级',
    unhealthy: '异常',
  }
  return map[health.value.status] || health.value.status || '未知'
})

const serviceList = computed(() => {
  const checks = health.value.checks || {}
  const services: { name: string; ok: boolean; detail: string }[] = []

  const redis = checks.redis
  services.push({
    name: 'Redis',
    ok: redis === 'available',
    detail: typeof redis === 'string' ? redis : '—',
  })

  const llm = checks.llm_gateway
  services.push({
    name: 'LLM 网关',
    ok: llm === 'available',
    detail: typeof llm === 'string' ? llm : '—',
  })

  const pool = checks.agent_pool as { status?: string; size?: number } | undefined
  services.push({
    name: 'Agent 池',
    ok: pool?.status === 'available',
    detail: pool?.size !== undefined ? `${pool.size} 个` : '—',
  })

  const skill = checks.skill_registry as { status?: string; count?: number } | undefined
  services.push({
    name: '技能注册表',
    ok: skill?.status === 'available',
    detail: skill?.count !== undefined ? `${skill.count} 个` : '—',
  })

  return services
})

let refreshTimer: number | null = null

async function refreshData(): Promise<void> {
  // 首次加载显示 loading spinner；后续定时刷新静默更新数据，不切换 DOM，
  // 避免面板每 10 秒 reload 到 spinner 再回来的视觉闪烁。
  if (initialLoading.value) {
    loading.value = true
    error.value = ''
  }
  try {
    const [h, m] = await Promise.all([
      getHealth().catch((e: unknown) => {
        const msg = e instanceof Error ? e.message : '未知错误'
        throw new Error(`健康检查失败: ${msg}`)
      }),
      getMetrics().catch((e: unknown) => {
        const msg = e instanceof Error ? e.message : '未知错误'
        throw new Error(`指标获取失败: ${msg}`)
      }),
    ])
    health.value = h
    metrics.value = m
    // 刷新成功清除 error（静默恢复）
    error.value = ''
  } catch (e: unknown) {
    const msg = e instanceof Error ? e.message : '加载失败'
    // 首次加载失败必须显示 error；后续刷新失败保持当前数据，不打断用户
    if (initialLoading.value) {
      error.value = msg
    }
  } finally {
    loading.value = false
    initialLoading.value = false
  }
}

onMounted(() => {
  refreshData()
  refreshTimer = window.setInterval(refreshData, 10000)
})

onUnmounted(() => {
  if (refreshTimer !== null) {
    clearInterval(refreshTimer)
  }
})
</script>

<style scoped>
.system-monitor {
  display: flex;
  flex-direction: row;
  height: 100%;
  background: var(--bg-primary);
  border-left: 1px solid var(--border-color);
}

.system-monitor__content {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 所有 Tab 内容组件自动填充高度 */
.system-monitor__content > * {
  flex: 1;
  min-height: 0;
}

/* monitor 标签页需要自己的 flex 列布局以支持子元素滚动和居中 */
.system-monitor__monitor {
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.system-monitor__tabs {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: var(--space-1);
  padding: var(--space-3) var(--space-1);
  border-left: 1px solid var(--border-color);
  background: var(--bg-secondary);
  flex-shrink: 0;
  width: 44px;
}

.system-monitor__tab {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  cursor: pointer;
  padding: 0;
  border: none;
  border-left: 2px solid transparent;
  background: transparent;
  color: var(--text-tertiary);
  font-family: inherit;
  transition: color 0.15s, background 0.15s;
  border-radius: var(--radius-md);
}

.system-monitor__tab:hover {
  color: var(--text-primary);
  background: var(--bg-tertiary);
}

.system-monitor__tab--active {
  color: var(--color-primary);
  background: var(--color-primary-light);
  /* ponytail: override the transparent border-left so the active indicator is visible */
  border-left-color: var(--color-primary);
}

.system-monitor__tab-icon {
  font-size: 16px;
}

.system-monitor__loading,
.system-monitor__error {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: var(--space-2);
  color: var(--text-tertiary);
  font-size: var(--font-sm);
}

.system-monitor__error {
  color: var(--color-error);
}

.system-monitor__body {
  flex: 1;
  overflow-y: auto;
  padding: 18px 16px;
}

.system-monitor__section-title {
  font-size: var(--font-sm);
  font-weight: var(--font-weight-semibold);
  color: var(--text-primary);
  margin: 18px 0 12px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.system-monitor__section-title:first-child {
  margin-top: 0;
}

.system-monitor__section-title::before {
  content: '';
  display: inline-block;
  width: 3px;
  height: 12px;
  background: var(--color-primary);
  border-radius: 2px;
}

/* 系统概览区：4 个指标卡片 + 分隔线 */
.system-monitor__metrics {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
  padding-bottom: 22px;
  margin-bottom: 4px;
  border-bottom: 1px solid var(--border-color);
}

.system-monitor__metric {
  padding: 14px 12px;
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  background: var(--bg-secondary);
  transition: border-color 0.15s;
}

.system-monitor__metric:hover {
  border-color: var(--color-primary-light);
}

.system-monitor__metric-label {
  font-size: 11px;
  color: var(--text-tertiary);
  margin-bottom: 6px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.system-monitor__metric-value {
  font-size: 20px;
  font-weight: var(--font-weight-semibold);
  color: var(--text-primary);
  margin-bottom: 4px;
  line-height: 1.2;
}

.system-monitor__metric-value.status-healthy {
  color: var(--color-success);
}

.system-monitor__metric-value.status-degraded {
  color: var(--color-warning);
}

.system-monitor__metric-value.status-unhealthy,
.system-monitor__metric-value.status-unknown {
  color: var(--color-error);
}

.system-monitor__metric-delta {
  font-size: 10px;
  color: var(--text-tertiary);
  line-height: 1.4;
}

.system-monitor__metric-delta.up {
  color: var(--color-success);
}

.system-monitor__metric-delta.down {
  /* 队列中有任务 = 警告语义（不是 team 语义），用 warning 而非 --accent-team */
  color: var(--color-warning);
}

/* 分区容器：左右两列独立分块 */
.system-monitor__split {
  display: grid;
  grid-template-columns: 1fr;
  gap: 22px;
  margin-top: 6px;
}

.system-monitor__column {
  display: flex;
  flex-direction: column;
  min-width: 0;
}

/* 服务状态区：与上方 metrics 区域有明显的呼吸间距 */
.system-monitor__services {
  display: flex;
  flex-direction: column;
  gap: 0;
  padding: 6px 14px;
  background: var(--bg-secondary);
  border-radius: var(--radius-md);
  border: 1px solid var(--border-color);
  margin-top: 4px;
}

.system-monitor__service {
  display: grid;
  grid-template-columns: 10px minmax(0, 1fr) auto auto;
  align-items: center;
  gap: 10px;
  padding: 10px 0;
  font-size: var(--font-sm);
  border-bottom: 1px solid var(--border-color);
}

.system-monitor__service:last-child {
  border-bottom: none;
}

.system-monitor__service-name,
.system-monitor__service-status,
.system-monitor__service-time {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.system-monitor__service-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: var(--text-placeholder);
  box-shadow: 0 0 0 2px var(--bg-secondary);
}

.system-monitor__service-dot.ok {
  background: var(--color-success);
  box-shadow: 0 0 0 2px rgba(82, 196, 26, 0.12);
}

.system-monitor__service-dot.error {
  background: var(--color-error);
  box-shadow: 0 0 0 2px rgba(245, 34, 45, 0.12);
}

.system-monitor__service-name {
  color: var(--text-primary);
  font-weight: var(--font-weight-medium, 500);
}

.system-monitor__service-status {
  color: var(--color-success);
  font-size: 11px;
  padding: 1px 6px;
  border-radius: 3px;
  background: rgba(82, 196, 26, 0.08);
}

.system-monitor__service-time {
  color: var(--text-tertiary);
  font-size: 11px;
  text-align: right;
}

.system-monitor__chart-placeholder {
  min-height: 96px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: var(--space-2);
  color: var(--text-tertiary);
  font-size: var(--font-xs);
  background: var(--bg-secondary);
  border-radius: var(--radius-md);
  border: 1px dashed var(--border-color);
  margin-top: 4px;
  padding: 12px;
}
</style>
