<template>
  <v-container fluid class="pa-4 pa-md-6 dashboard-root">
    <!-- ── Stats Cards ── -->
    <v-row>
      <v-col
        v-for="(item, i) in statItems"
        :key="i"
        cols="6"
        sm="3"
      >
        <v-card
          elevation="0"
          rounded="xl"
          border
          class="stat-card"
        >
          <v-card-text class="pa-4 d-flex align-center justify-space-between">
            <div>
              <div class="text-caption text-medium-emphasis mb-1" style="font-size: 14px; letter-spacing: 0.5px; text-transform: uppercase">{{ item.subtitle }}</div>
              <div class="font-weight-bold" :class="'text-' + item.color" style="font-size: 36px; line-height: 1.1">{{ item.title }}</div>
            </div>
            <v-avatar :color="item.color" size="48" rounded="lg" class="stat-icon">
              <v-icon :icon="item.icon" size="24" color="white" />
            </v-avatar>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>

    <!-- ── Server Table (v-card border elevation-0, same as official "Recent Orders") ── -->
    <v-card class="my-5" elevation="0" rounded="lg" title="服务器列表" border>
      <template #text>
        <v-text-field
          v-model="search"
          autocomplete="off"
          placeholder="搜索..."
          prepend-inner-icon="mdi-magnify"
          variant="outlined"
          hide-details
          rounded
          class="mb-4"
        />

        <v-data-table-server
          :items="servers"
          :headers="headers"
          :items-length="total"
          :loading="loading"
          :page="page"
          :items-per-page="itemsPerPage"
          hover
          item-value="id"
          @update:page="onPageChange"
          @update:items-per-page="onItemsPerPageChange"
        >
          <template #item.status="{ item }">
            <v-chip
              :color="statusChipColor(item.status)"
              :text="statusLabel(item.status)"
              border="sm"
              size="x-small"
              label
            />
          </template>

          <template #item.name="{ item }">
            <span class="font-weight-medium">{{ item.name }}</span>
          </template>

          <template #item.domain="{ item }">
            <span class="text-medium-emphasis">{{ item.domain }}</span>
          </template>

          <template #item.category="{ item }">
            <span class="text-medium-emphasis">{{ item.category || '—' }}</span>
          </template>

          <template #item.agent_version="{ item }">
            <span class="text-medium-emphasis">{{ item.agent_version || '—' }}</span>
          </template>

          <template #item.last_heartbeat="{ item }">
            <span class="text-caption text-medium-emphasis">{{ formatRelativeTime(item.last_heartbeat) }}</span>
          </template>

          <template #item.actions="{ item }">
            <div class="d-flex ga-1">
              <v-btn variant="text" size="x-small" color="primary" density="compact" @click="openTerminal(item)">终端</v-btn>
              <v-btn variant="text" size="x-small" density="compact" @click="openFiles(item)">文件</v-btn>
            </div>
          </template>

          <template #no-data>
            <div class="text-center text-medium-emphasis py-6">暂无服务器数据</div>
          </template>
        </v-data-table-server>
      </template>
    </v-card>

    <!-- ── Bottom Row: Alerts + Summary ── -->
    <v-row>
      <v-col cols="12" md="6">
        <v-card elevation="0" rounded="lg" title="告警历史" border>
          <template #append>
            <div class="my-5" />
          </template>

          <template #text>
            <div v-if="recentAlerts.length === 0" class="text-center text-medium-emphasis py-4">
              暂无告警
            </div>
            <v-list-item
              v-for="(item, i) in recentAlerts"
              :key="i"
              :class="i !== 0 && 'mt-4'"
              :subtitle="item.subtitle"
              :title="item.title"
              class="px-0"
              lines="one"
            >
              <template #prepend>
                <v-avatar
                  :color="item.color"
                  :icon="item.icon"
                  variant="tonal"
                  rounded
                />
              </template>

              <template #append>
                <span class="text-body-large font-weight-regular">
                  {{ item.value }}
                </span>
              </template>
            </v-list-item>
          </template>
        </v-card>
      </v-col>

      <v-col cols="12" md="6">
        <v-card elevation="0" rounded="lg" title="资源概览" border>
          <template #append>
            <div class="my-5" />
          </template>

          <template #text>
            <v-list-item
              v-for="(item, i) in summaryItems"
              :key="i"
              :class="i !== 0 && 'mt-4'"
              class="px-0"
            >
              <template #prepend>
                <v-avatar :text="item.text" color="primary" size="large" variant="tonal" />
              </template>

              <template #title>
                <div class="d-flex justify-space-between align-center text-medium-emphasis">
                  <span>{{ item.title }}</span>
                  <span>{{ item.value }}</span>
                </div>
              </template>

              <template #subtitle>
                <div class="py-1">
                  <v-progress-linear
                    :model-value="item.progress"
                    bg-color="surface-light"
                    bg-opacity="1"
                    color="primary"
                    height="8"
                    rounded
                  />
                </div>
              </template>
            </v-list-item>
          </template>
        </v-card>
      </v-col>
    </v-row>

    <!-- ── Second Row: Categories + Recent Audit ── -->
    <v-row>
      <v-col cols="12" md="6">
        <v-card elevation="0" rounded="lg" title="分类分布" border>
          <template #text>
            <div v-if="Object.keys(categories).length === 0" class="text-center text-medium-emphasis py-4">
              暂无分类数据
            </div>
            <v-list-item
              v-for="(count, name) in categories"
              :key="name"
              class="px-0"
            >
              <template #prepend>
                <v-avatar color="primary" variant="tonal" size="small">
                  <span class="text-caption">{{ (name as string)[0]?.toUpperCase() }}</span>
                </v-avatar>
              </template>
              <template #title>
                <div class="d-flex justify-space-between align-center">
                  <span class="text-medium-emphasis">{{ name === 'uncategorized' ? '未分类' : name }}</span>
                  <span class="text-body-2 font-weight-medium">{{ count }} 台</span>
                </div>
              </template>
              <template #subtitle>
                <v-progress-linear
                  :model-value="statsTotal > 0 ? (count / statsTotal) * 100 : 0"
                  bg-color="surface-light"
                  bg-opacity="1"
                  color="primary"
                  height="6"
                  rounded
                />
              </template>
            </v-list-item>
          </template>
        </v-card>
      </v-col>

      <v-col cols="12" md="6">
        <v-card elevation="0" rounded="lg" title="最近操作" border>
          <template #append>
            <v-btn size="small" variant="text" to="/audit">查看全部</v-btn>
          </template>
          <template #text>
            <div v-if="recentAudit.length === 0" class="text-center text-medium-emphasis py-4">
              暂无操作记录
            </div>
            <v-list-item
              v-for="item in recentAudit"
              :key="item.id"
              :title="auditSummary(item)"
              :subtitle="`${item.admin_username} · ${formatRelativeTime(item.created_at)}`"
              class="px-0"
              lines="two"
            >
              <template #append>
                <v-chip size="x-small" variant="tonal" label>{{ item.ip_address || '—' }}</v-chip>
              </template>
            </v-list-item>
          </template>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>

<style scoped>
.stat-card {
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 24px rgba(var(--v-theme-primary), 0.08) !important;
}
.stat-icon {
  transition: transform 0.3s ease;
}
.stat-card:hover .stat-icon {
  transform: scale(1.1);
}
.dashboard-root {
  min-width: 0;
  max-width: 100%;
}
.dashboard-root :deep(.v-table) {
  overflow-x: auto;
}
</style>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { http } from '@/api'
import { useSnackbar } from '@/composables/useSnackbar'
import { useWebSocket } from '@/composables/useWebSocket'
import { useServerPagination } from '@/composables/useServerPagination'
import { statusChipColor, statusLabel, formatRelativeTime } from '@/utils/status'
import { auditSummary } from '@/utils/auditLabels'
import { normalizeAuditList } from '@/utils/auditNormalize'
import type { ServerApiItem, AuditItem, AlertLogItem } from '@/types/api'

const snackbar = useSnackbar()

const router = useRouter()

// ── Stats ──
const statItems = ref([
  { subtitle: '服务器总数', title: '0', icon: 'mdi-server-network', color: 'blue' },
  { subtitle: '在线', title: '0', icon: 'mdi-check-circle-outline', color: 'green' },
  { subtitle: '离线', title: '0', icon: 'mdi-alert-circle-outline', color: 'orange' },
  { subtitle: '告警中', title: '0', icon: 'mdi-bell-alert-outline', color: 'red' },
])

// ── Server Table (composable) ──
const {
  servers, loading, page, itemsPerPage, total, search,
  loadServers: _loadServers, onSearch, onPageChange, onItemsPerPageChange,
} = useServerPagination()

async function loadServers() {
  try {
    await _loadServers()
  } catch {
    snackbar('加载服务器列表失败', 'error')
  }
}

const headers = [
  { title: '状态', key: 'status', width: 100 },
  { title: '名称', key: 'name' },
  { title: '地址', key: 'domain' },
  { title: '分类', key: 'category', width: 100 },
  { title: 'Agent', key: 'agent_version', width: 100 },
  { title: '心跳', key: 'last_heartbeat', width: 140 },
  { title: '操作', key: 'actions', width: 140, align: 'end' as const },
]

// ── Alerts ──
const recentAlerts = ref<AlertItem[]>([])

// ── Summary ──
const summaryItems = ref([
  { title: '在线率', progress: 0, text: '在', value: '0%' },
  { title: 'Agent 覆盖', progress: 0, text: 'A', value: '0%' },
  { title: 'CPU 平均', progress: 0, text: 'C', value: '0%' },
  { title: '内存平均', progress: 0, text: 'M', value: '0%' },
])

// ── Categories ──
const categories = ref<Record<string, number>>({})
const statsTotal = ref(0)

// ── Recent Audit ──
const recentAudit = ref<AuditItem[]>([])

// ── Data Loading ──
async function loadStats() {
  try {
    const s = await http.get<{ total: number; online: number; offline: number; alerts: number; categories: Record<string, number> }>('/servers/stats')
    statItems.value[0].title = String(s.total)
    statItems.value[1].title = String(s.online)
    statItems.value[2].title = String(s.offline)
    statItems.value[3].title = String(s.alerts ?? 0)

    // Capture categories and total for distribution chart
    categories.value = s.categories || {}
    statsTotal.value = s.total

    // Update summary
    const onlineRate = s.total ? Math.round((s.online / s.total) * 100) : 0
    summaryItems.value[0].progress = onlineRate
    summaryItems.value[0].value = `${onlineRate}%`
  } catch {
    snackbar('加载统计数据失败', 'error')
  }
}

async function loadAlerts() {
  try {
    const res = await http.get<{ items: AlertLogItem[] }>('/alert-history/', { limit: 5 })
    recentAlerts.value = (res.items || []).map(a => ({
      title: a.server_name,
      subtitle: `${a.alert_type} ${a.is_recovery ? '(已恢复)' : ''} · ${formatRelativeTime(a.created_at)}`,
      value: a.value,
      color: a.is_recovery ? 'green' : 'red',
      icon: a.is_recovery ? 'mdi-check-circle' : 'mdi-alert-circle',
    }))
  } catch {
    recentAlerts.value = []
  }
}

async function loadRecentAudit() {
  try {
    const res = await http.get<{ items: unknown[] }>('/audit/', { limit: 10 })
    recentAudit.value = normalizeAuditList(res.items || []).slice(0, 10)
  } catch { recentAudit.value = [] }
}

async function loadSummary() {
  try {
    // Load a larger set to compute fleet-wide stats
    const res = await http.get<{ items: ServerApiItem[]; total: number }>('/servers/', { per_page: 200 })
    const allServers = res.items || []
    const fleetTotal = res.total || allServers.length

    if (fleetTotal === 0) return

    // Agent coverage
    const withAgent = allServers.filter(s => s.agent_version).length
    const agentRate = Math.round((withAgent / fleetTotal) * 100)
    summaryItems.value[1].progress = agentRate
    summaryItems.value[1].value = `${agentRate}%`

    // CPU / Memory averages (from servers with system_info)
    const withCpu = allServers.filter(s => s.system_info?.cpu_usage != null)
    const withMem = allServers.filter(s => s.system_info?.mem_usage != null)

    if (withCpu.length > 0) {
      const cpuAvg = Math.round(withCpu.reduce((sum, s) => sum + (s.system_info!.cpu_usage || 0), 0) / withCpu.length)
      summaryItems.value[2].progress = cpuAvg
      summaryItems.value[2].value = `${cpuAvg}%`
    }
    if (withMem.length > 0) {
      const memAvg = Math.round(withMem.reduce((sum, s) => sum + (s.system_info!.mem_usage || 0), 0) / withMem.length)
      summaryItems.value[3].progress = memAvg
      summaryItems.value[3].value = `${memAvg}%`
    }
  } catch {
    // Summary stats are non-critical, leave at previous values
  }
}

function openTerminal(item: ServerApiItem) {
  router.push({ path: '/terminal', query: { server_id: String(item.id) } })
}
function openFiles(item: ServerApiItem) {
  router.push({ path: '/files', query: { server_id: String(item.id) } })
}

// ── Init ──
// NOTE: WebSocket is managed by App.vue (connected when auth.isLoggedIn=true),
// so we reuse that global singleton instead of creating a second connection.
const ws = useWebSocket()
watch(ws.alerts, () => {
  loadStats()
  loadAlerts()
})

onMounted(() => {
  loadStats()
  loadServers()
  loadAlerts()
  loadSummary()
  loadRecentAudit()
})

interface AlertItem {
  title: string
  subtitle: string
  value: string
  color: string
  icon: string
}
</script>
