<template>
  <div class="page">
    <PageHeader
      :title="t('dashboard.title')"
      :description="t('dashboard.description')"
    />

    <div class="stat-grid">
      <StatCard :label="t('dashboard.requests24h')" :value="overview?.total_requests_24h ?? 0" />
      <StatCard :label="t('dashboard.tokens24h')" :value="formatNumberCompact(overview?.total_tokens_24h ?? 0)" />
      <StatCard :label="t('dashboard.errorRate')" :value="((overview?.error_rate ?? 0) * 100).toFixed(2) + '%'" />
      <StatCard :label="t('dashboard.activeIngressKeys')" :value="overview?.active_ingress_keys ?? 0" />
    </div>

    <div class="content-grid content-grid--2">
      <AppCard :title="t('dashboard.requestTrend')">
        <ChartBox :option="requestChartOption" />
      </AppCard>
      <AppCard :title="t('dashboard.tokenTrend')">
        <ChartBox :option="tokenChartOption" />
      </AppCard>
    </div>

    <div class="content-grid content-grid--2-1">
      <AppCard :title="t('dashboard.providerHealth')">
        <el-table :data="providers" size="small">
          <el-table-column prop="name" :label="t('common.name')" />
          <el-table-column prop="type" :label="t('common.type')" width="120" />
          <el-table-column :label="t('common.status')" width="110">
            <template #default="{ row }">
              <el-tag :type="statusType(row.health?.status || row.status)" size="small">
                {{ row.health?.status || row.status || 'unknown' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column :label="t('common.latencyMs')" width="100">
            <template #default="{ row }">
              <span :class="metricStatusClass(row.health?.latency_ms)">{{ row.health?.latency_ms ?? t('common.dash') }}</span>
            </template>
          </el-table-column>
        </el-table>
      </AppCard>

      <AppCard :title="t('dashboard.ingressTop5')">
        <el-table :data="ingressUsage" size="small">
          <el-table-column prop="name" :label="t('common.name')" />
          <el-table-column prop="request_count" :label="t('common.requests')" width="80" />
          <el-table-column prop="token_count" :label="t('common.tokens')" width="90" />
        </el-table>
      </AppCard>
    </div>

    <div class="content-grid content-grid--2-1">
      <AppCard :title="t('dashboard.providerModelUsage')">
        <el-table :data="providerModelUsage" size="small">
          <el-table-column prop="provider_name" label="Provider" min-width="120" show-overflow-tooltip />
          <el-table-column prop="model" :label="t('common.model')" min-width="160" show-overflow-tooltip />
          <el-table-column prop="request_count" :label="t('common.requests')" width="80" />
          <el-table-column prop="token_count" :label="t('common.tokens')" width="90" />
          <el-table-column :label="t('common.cost')" width="100">
            <template #default="{ row }">{{ row.cost.toFixed(4) }}</template>
          </el-table-column>
        </el-table>
      </AppCard>

      <AppCard :title="t('dashboard.clientIpUsage')">
        <el-table :data="clientIPUsage" size="small">
          <el-table-column prop="client_ip" :label="t('dashboard.clientIp')" min-width="140" />
          <el-table-column prop="request_count" :label="t('common.requests')" width="80" />
          <el-table-column prop="token_count" :label="t('common.tokens')" width="90" />
          <el-table-column :label="t('common.cost')" width="100">
            <template #default="{ row }">{{ row.cost.toFixed(4) }}</template>
          </el-table-column>
        </el-table>
      </AppCard>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import type { EChartsOption } from 'echarts'
import api, {
  type ClientIPUsage,
  type DashboardOverview,
  type IngressKey,
  type ProviderModelUsage,
  type RequestTrendBucket,
} from '@/api/client'
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 { buildTrendChartOption } from '@/utils/chartTheme'
import { formatChartHour, formatNumberCompact } from '@/utils/format'

const { t, locale } = useI18n()

const overview = ref<DashboardOverview | null>(null)
const providers = ref<any[]>([])
const ingressUsage = ref<IngressKey[]>([])
const providerModelUsage = ref<ProviderModelUsage[]>([])
const clientIPUsage = ref<ClientIPUsage[]>([])
const trend = ref<RequestTrendBucket[]>([])
let timer: number

const chartLabels = computed(() =>
  trend.value.map((b) => formatChartHour(b.hour, locale.value)),
)

const requestChartOption = computed<EChartsOption>(() =>
  buildTrendChartOption({
    labels: chartLabels.value,
    series: [
      { name: t('dashboard.seriesRequests'), data: trend.value.map((b) => b.requests), colorIndex: 0 },
      { name: t('dashboard.seriesErrors'), data: trend.value.map((b) => b.errors), colorIndex: 1 },
    ],
  }),
)

const tokenChartOption = computed<EChartsOption>(() =>
  buildTrendChartOption({
    labels: chartLabels.value,
    series: [
      { name: t('dashboard.seriesTokens'), data: trend.value.map((b) => b.tokens), colorIndex: 0 },
    ],
  }),
)

function statusType(s: string) {
  if (s === 'healthy') return 'success'
  if (s === 'unhealthy') return 'danger'
  return 'warning'
}

function metricStatusClass(ms?: number) {
  if (ms == null) return 'status-muted'
  if (ms < 500) return 'status-good'
  if (ms < 2000) return 'status-warn'
  return 'status-bad'
}

async function load() {
  const [o, p, i, pm, ip, tr] = await Promise.all([
    api.get('/dashboard/overview'),
    api.get('/dashboard/providers'),
    api.get('/dashboard/ingress-usage'),
    api.get('/dashboard/provider-model-usage'),
    api.get('/dashboard/client-ip-usage'),
    api.get('/dashboard/request-trend'),
  ])
  overview.value = o.data
  providers.value = p.data.data
  ingressUsage.value = [...i.data.data].sort((a, b) => b.request_count - a.request_count).slice(0, 5)
  providerModelUsage.value = pm.data.data
  clientIPUsage.value = ip.data.data
  trend.value = tr.data.data
}

onMounted(() => {
  load()
  timer = window.setInterval(load, 15000)
})
onUnmounted(() => clearInterval(timer))
</script>
