<template>
  <v-container fluid class="pa-4 pa-md-6 dashboard-root">
    <StatCardsRow
      :items="statItemsDisplay"
      :loading="statsBooting"
      :refreshing="statsRefreshing"
      @click="onStatCardClick"
      @refresh="refreshStatCards"
    />

    <v-row class="mt-5">
      <v-col cols="12">
        <DashboardFleetTrends ref="fleetTrendsRef" />
      </v-col>
    </v-row>

    <!-- ── Bottom Row: Alerts + Summary ── -->
    <v-row class="mt-5">
      <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>
.dashboard-root {
  min-width: 0;
  max-width: 100%;
}
</style>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { http } from '@/api'
import { useSnackbar } from '@/composables/useSnackbar'
import { useWebSocket } from '@/composables/useWebSocket'
import { usePageActivateRefresh } from '@/composables/usePageActivateRefresh'
import {
  SERVER_STAT_CARD_KEYS,
  applyServerStats,
  fetchServerStats,
  refreshServerStats,
  useServerStatsCards,
} from '@/composables/useServerStatsCards'
import { formatRelativeTime } from '@/utils/status'
import { auditSummary } from '@/utils/auditLabels'
import { normalizeAuditList } from '@/utils/auditNormalize'
import type { ServerApiItem, AuditItem, AlertLogItem } from '@/types/api'
import StatCardsRow from '@/components/StatCardsRow.vue'
import DashboardFleetTrends from '@/components/dashboard/DashboardFleetTrends.vue'

defineOptions({ name: 'DashboardPage' })

const snackbar = useSnackbar()
const router = useRouter()
const fleetTrendsRef = ref<InstanceType<typeof DashboardFleetTrends> | null>(null)

const statsBooting = ref(true)
const statsRefreshing = ref(false)

// ── Stats（与服务器页同源 composable，可点击跳转）──
const { statItems } = useServerStatsCards()

const statItemsDisplay = computed(() =>
  statItems.value.map((item, i) => {
    const key = SERVER_STAT_CARD_KEYS[i]
    return {
      ...item,
      key,
      clickable: key !== 'total',
    }
  }),
)

function onStatCardClick(key: string) {
  if (key === 'alerts') {
    router.push({ path: '/alerts' })
    return
  }
  if (key === 'online') {
    router.push({ path: '/servers' })
    return
  }
  if (key === 'offline') {
    router.push({ path: '/servers', query: { status: 'offline' } })
    return
  }
  if (key === 'unset-path') {
    router.push({ path: '/servers', query: { unset_path: '1' } })
  }
}

// ── 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(silent = false) {
  if (!silent) statsBooting.value = true
  try {
    const s = await fetchServerStats()
    applyServerStats(statItems, s)
    applyStatsSideEffects(s)
  } catch {
    if (!silent) snackbar('加载统计数据失败', 'error')
  } finally {
    if (!silent) statsBooting.value = false
  }
}

function applyStatsSideEffects(s: Awaited<ReturnType<typeof fetchServerStats>>) {
  categories.value = s.categories || {}
  statsTotal.value = s.total
  const onlineRate = s.total ? Math.round((s.online / s.total) * 100) : 0
  summaryItems.value[0].progress = onlineRate
  summaryItems.value[0].value = `${onlineRate}%`
}

async function refreshStatCards() {
  statsRefreshing.value = true
  try {
    const s = await refreshServerStats(statItems)
    applyStatsSideEffects(s)
  } catch {
    snackbar('刷新统计数据失败', 'error')
  } finally {
    statsRefreshing.value = false
  }
}

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 = []
    snackbar('加载告警记录失败', 'error')
  }
}

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 = []
    snackbar('加载审计记录失败', 'error')
  }
}

async function loadSummary() {
  try {
    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

    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}%`

    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
  }
}

async function refreshDashboard(silent = false) {
  await Promise.all([
    loadStats(silent),
    loadAlerts(),
    loadSummary(),
    loadRecentAudit(),
    fleetTrendsRef.value?.reload?.(),
  ])
  if (!silent) {
    http.post('/settings/bing-wallpapers/sync').catch(() => {})
  }
}

const ws = useWebSocket()
watch(ws.alerts, () => {
  void loadStats(true)
  void loadAlerts()
})

usePageActivateRefresh((silent) => refreshDashboard(silent))

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