<template>
  <section class="space-y-6">
    <header>
      <h1 class="mos-title text-2xl font-semibold">实时监控</h1>
      <p class="mos-muted mt-2 text-sm">实时监控活动数据与系统运行状态。</p>
    </header>

    <section class="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
      <div v-for="card in realtimeKPIs" :key="card.label" class="mos-card p-5">
        <div class="flex items-center justify-between">
          <div class="text-xs font-semibold text-mosquito-ink/70">{{ card.label }}</div>
          <span class="rounded-full bg-green-100 px-2 py-1 text-[10px] font-semibold text-green-600">
            实时
          </span>
        </div>
        <div class="mos-kpi mt-4 text-2xl font-semibold text-mosquito-ink">{{ formatNumber(card.value) }}</div>
        <div class="mos-muted mt-2 text-xs">{{ card.hint }}</div>
      </div>
    </section>

    <section class="grid gap-6 lg:grid-cols-2">
      <div class="mos-card p-5">
        <h2 class="mos-title text-lg font-semibold">实时访问趋势</h2>
        <p class="mos-muted mt-1 text-xs">最近24小时访问量趋势</p>
        <div class="mt-4 h-48 flex items-center justify-center rounded-xl border border-dashed border-mosquito-line">
          <div v-if="hourlyTrend.length > 0" class="w-full h-full p-2">
            <div class="flex items-end justify-between h-full gap-1">
              <div v-for="point in hourlyTrend" :key="point.hour" class="flex-1 flex flex-col items-center">
                <div
                  class="w-full bg-mosquito-primary rounded-t"
                  :style="{ height: getBarHeight(point.visits) + '%', minHeight: '4px' }"
                ></div>
                <span class="text-[8px] text-mosquito-ink/50 mt-1">{{ point.hour.split(':')[0] }}</span>
              </div>
            </div>
          </div>
          <span v-else class="text-sm text-mosquito-ink/60">暂无数据</span>
        </div>
      </div>

      <div class="mos-card p-5">
        <h2 class="mos-title text-lg font-semibold">系统健康状态</h2>
        <p class="mos-muted mt-1 text-xs">后端服务与数据库状态</p>
        <div class="mt-4 space-y-3">
          <div class="flex items-center justify-between rounded-lg px-4 py-3" :class="systemHealth.backend?.status === 'UP' ? 'bg-green-50' : 'bg-red-50'">
            <span class="text-sm font-medium" :class="systemHealth.backend?.status === 'UP' ? 'text-green-700' : 'text-red-700'">后端服务</span>
            <span class="rounded-full px-2 py-1 text-xs font-semibold" :class="systemHealth.backend?.status === 'UP' ? 'bg-green-200 text-green-700' : 'bg-red-200 text-red-700'">
              {{ systemHealth.backend?.status === 'UP' ? '正常' : '异常' }}
            </span>
          </div>
          <div class="flex items-center justify-between rounded-lg px-4 py-3" :class="systemHealth.database?.status === 'UP' ? 'bg-green-50' : 'bg-red-50'">
            <span class="text-sm font-medium" :class="systemHealth.database?.status === 'UP' ? 'text-green-700' : 'text-red-700'">数据库连接</span>
            <span class="rounded-full px-2 py-1 text-xs font-semibold" :class="systemHealth.database?.status === 'UP' ? 'bg-green-200 text-green-700' : 'bg-red-200 text-red-700'">
              {{ systemHealth.database?.status === 'UP' ? '正常' : '异常' }}
            </span>
          </div>
          <div class="flex items-center justify-between rounded-lg px-4 py-3" :class="systemHealth.redis?.status === 'UP' ? 'bg-green-50' : 'bg-red-50'">
            <span class="text-sm font-medium" :class="systemHealth.redis?.status === 'UP' ? 'text-green-700' : 'text-red-700'">Redis缓存</span>
            <span class="rounded-full px-2 py-1 text-xs font-semibold" :class="systemHealth.redis?.status === 'UP' ? 'bg-green-200 text-green-700' : 'bg-red-200 text-red-700'">
              {{ systemHealth.redis?.status === 'UP' ? '正常' : '异常' }}
            </span>
          </div>
        </div>
      </div>
    </section>

    <section class="mos-card p-5">
      <h2 class="mos-title text-lg font-semibold">实时事件流</h2>
      <p class="mos-muted mt-1 text-xs">最新系统事件与用户行为</p>
      <div class="mt-4 space-y-2">
        <div v-for="event in recentEvents" :key="event.id" class="flex items-center justify-between rounded-lg border border-mosquito-line px-4 py-2 text-sm">
          <span class="text-mosquito-ink">{{ event.description }}</span>
          <span class="text-mosquito-ink/60">{{ event.time }}</span>
        </div>
        <div v-if="!recentEvents.length" class="text-center text-sm text-mosquito-ink/60 py-4">
          暂无实时事件
        </div>
      </div>
    </section>
  </section>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getRealtimeData, type RealtimeData } from '@/services/dashboard'

type RealtimeEvent = {
  id: string
  description: string
  time: string
}

type HourlyPoint = {
  hour: string
  visits: number
}

const formatNumber = (value: number | null) => {
  if (value === null || Number.isNaN(value)) {
    return '--'
  }
  return value.toLocaleString('zh-CN')
}

const realtimeKPIs = ref([
  { label: '当前在线', value: 0, hint: '当前活跃用户数' },
  { label: '今日访问', value: 0, hint: '今日页面访问次数' },
  { label: '实时转化', value: 0, hint: '当前转化率' },
  { label: 'API请求', value: 0, hint: 'API调用次数' }
])

const recentEvents = ref<RealtimeEvent[]>([])
const hourlyTrend = ref<HourlyPoint[]>([])
const systemHealth = ref<{
  backend?: { status: string; message: string }
  database?: { status: string; message: string }
  redis?: { status: string; message: string }
}>({})

const getBarHeight = (visits: number) => {
  if (!hourlyTrend.value.length) return 0
  const maxVisits = Math.max(...hourlyTrend.value.map(p => p.visits))
  if (maxVisits === 0) return 10
  return Math.max((visits / maxVisits) * 100, 10)
}

onMounted(async () => {
  try {
    const data: RealtimeData = await getRealtimeData()
    realtimeKPIs.value = [
      { label: '当前在线', value: data.currentOnline, hint: '当前活跃用户数' },
      { label: '今日访问', value: data.todayVisits, hint: '今日页面访问次数' },
      { label: '实时转化', value: data.realtimeConversion, hint: '当前转化率(%)' },
      { label: 'API请求', value: data.apiRequests, hint: 'API调用次数' }
    ]
    hourlyTrend.value = data.hourlyTrend || []
    systemHealth.value = data.systemHealth || {}
    recentEvents.value = data.recentEvents || []
  } catch (error) {
    console.error('Failed to load realtime data:', error)
  }
})
</script>
