<template>
  <div class="page">
    <PageHeader :title="t('dashboard.title')" :description="t('dashboard.description')">
      <template #actions>
        <el-button @click="load">{{ t('common.refresh') }}</el-button>
        <el-button link type="primary" @click="openApiDoc">{{ t('dashboard.openapi') }}</el-button>
      </template>
    </PageHeader>

    <div class="stat-grid">
      <StatCard v-for="item in statCards" :key="item.labelKey" :label="t(item.labelKey)" :value="item.value" />
    </div>

    <div class="content-grid content-grid--2">
      <AppCard :title="t('dashboard.systemResources')" padded>
        <div class="kv-block">
          <p><span class="label">{{ t('dashboard.cpu') }}</span><span>{{ data.cpu_percent?.toFixed?.(1) ?? 0 }}%</span></p>
          <p><span class="label">{{ t('dashboard.memory') }}</span><span>{{ data.mem_percent?.toFixed?.(1) ?? 0 }}%</span></p>
          <p><span class="label">{{ t('dashboard.load') }}</span><span>{{ data.load1?.toFixed?.(2) ?? 0 }}</span></p>
        </div>
      </AppCard>
      <AppCard :title="t('dashboard.trafficOverview')" padded>
        <div class="kv-block">
          <p><span class="label">{{ t('dashboard.inlet') }}</span><span>{{ formatBytes(data.inlet_flow) }}</span></p>
          <p><span class="label">{{ t('dashboard.export') }}</span><span>{{ formatBytes(data.export_flow) }}</span></p>
        </div>
      </AppCard>
    </div>

    <div class="content-grid content-grid--2">
      <AppCard :title="t('dashboard.resourceTrend')" padded>
        <ChartBox :option="resourceChartOption" />
      </AppCard>
      <AppCard :title="t('dashboard.trafficTrend')" padded>
        <ChartBox :option="trafficChartOption" />
      </AppCard>
    </div>

    <div class="content-grid content-grid--3">
      <AppCard>
        <template #header>
          <div class="card-header-row">
            <h3 class="app-card__title">{{ t('dashboard.tunnelTop10') }}</h3>
            <el-button link type="primary" @click="openRank('tunnels', t('dashboard.rankTunnels'))">{{ t('common.viewAll') }}</el-button>
          </div>
        </template>
        <el-table :data="data.top_tunnels || []" size="small">
          <el-table-column prop="name" :label="t('common.name')" />
          <el-table-column :label="t('common.traffic')">
            <template #default="{ row }">{{ formatBytes((row.inlet_flow || 0) + (row.export_flow || 0)) }}</template>
          </el-table-column>
        </el-table>
      </AppCard>
      <AppCard>
        <template #header>
          <div class="card-header-row">
            <h3 class="app-card__title">{{ t('dashboard.hostTop10') }}</h3>
            <el-button link type="primary" @click="openRank('hosts', t('dashboard.rankHosts'))">{{ t('common.viewAll') }}</el-button>
          </div>
        </template>
        <el-table :data="data.top_hosts || []" size="small">
          <el-table-column prop="host" :label="t('dashboard.host')" />
          <el-table-column :label="t('common.traffic')">
            <template #default="{ row }">{{ formatBytes((row.inlet_flow || 0) + (row.export_flow || 0)) }}</template>
          </el-table-column>
        </el-table>
      </AppCard>
      <AppCard>
        <template #header>
          <div class="card-header-row">
            <h3 class="app-card__title">{{ t('dashboard.ipTop10') }}</h3>
            <el-button link type="primary" @click="openRank('ips', t('dashboard.rankIps'))">{{ t('common.viewAll') }}</el-button>
          </div>
        </template>
        <el-table :data="data.top_ips || []" size="small">
          <el-table-column prop="ip" :label="t('dashboard.visitorIp')" />
          <el-table-column prop="resource_label" :label="t('common.resource')" min-width="140" show-overflow-tooltip />
          <el-table-column prop="hit_count" :label="t('dashboard.hitCount')" width="72" />
        </el-table>
      </AppCard>
    </div>

    <RankDialog v-model="rankVisible" :type="rankType" :title="rankTitle" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useI18n } from 'vue-i18n'
import PageHeader from '@/components/PageHeader.vue'
import StatCard from '@/components/StatCard.vue'
import AppCard from '@/components/AppCard.vue'
import ChartBox from '@/components/ChartBox.vue'
import RankDialog from '@/components/RankDialog.vue'
import api from '@/api'
import { formatBytes } from '@/utils/format'
import { buildLineChartOption } from '@/utils/chartTheme'
import { useMetricHistory } from '@/composables/useMetricHistory'

const { t } = useI18n()
const data = ref({})
let timer
const rankVisible = ref(false)
const rankType = ref('tunnels')
const rankTitle = ref('')
const history = useMetricHistory()

const statCards = computed(() => [
  { labelKey: 'dashboard.statClientTotal', value: data.value.client_total ?? 0 },
  { labelKey: 'dashboard.statClientOnline', value: data.value.client_online ?? 0 },
  { labelKey: 'dashboard.statTunnelRunning', value: data.value.tunnel_running ?? 0 },
  { labelKey: 'dashboard.statHostTotal', value: data.value.host_total ?? 0 },
])

const resourceChartOption = computed(() => buildLineChartOption({
  labels: history.labels.value,
  series: [
    { name: t('dashboard.cpu'), data: history.cpu.value },
    { name: t('dashboard.memory'), data: history.memory.value },
  ],
  yAxisFormatter: (v) => `${v}%`,
}))

const trafficChartOption = computed(() => buildLineChartOption({
  labels: history.labels.value,
  series: [
    { name: t('dashboard.inlet'), data: history.inlet.value },
    { name: t('dashboard.export'), data: history.exportFlow.value },
  ],
  yAxisFormatter: (v) => formatBytes(v),
}))

async function load() {
  const { data: d } = await api.get('/dashboard')
  data.value = d
  history.record(d)
}

function openRank(type, title) {
  rankType.value = type
  rankTitle.value = title
  rankVisible.value = true
}

function openApiDoc() {
  window.open('/api/openapi.json', '_blank')
}

onMounted(() => {
  load()
  timer = setInterval(load, 5000)
})

onUnmounted(() => clearInterval(timer))
</script>
