<template>
  <div class="dashboard-view">
    <a-page-header
      title="管理概览"
      sub-title="系统状态总览与快捷入口"
      class="dashboard-view__header"
    />

    <a-spin :spinning="loading">
      <div class="dashboard-view__body">
        <a-row :gutter="16">
          <a-col :xs="24" :sm="12" :lg="6">
            <a-card class="dashboard-view__stat-card" hoverable @click="router.push('/admin/departments')">
              <a-statistic title="部门总数" :value="stats.departments" />
              <div class="dashboard-view__stat-hint">点击管理部门</div>
            </a-card>
          </a-col>
          <a-col :xs="24" :sm="12" :lg="6">
            <a-card class="dashboard-view__stat-card" hoverable @click="router.push('/admin/users')">
              <a-statistic title="用户总数" :value="stats.users" />
              <div class="dashboard-view__stat-hint">点击管理用户</div>
            </a-card>
          </a-col>
          <a-col :xs="24" :sm="12" :lg="6">
            <a-card class="dashboard-view__stat-card" hoverable @click="router.push('/admin/skills')">
              <a-statistic title="Skill 数量" :value="stats.skills" />
              <div class="dashboard-view__stat-hint">点击管理 Skill</div>
            </a-card>
          </a-col>
          <a-col :xs="24" :sm="12" :lg="6">
            <a-card class="dashboard-view__stat-card" hoverable @click="router.push('/admin/kb')">
              <a-statistic title="KB 文档数量" :value="stats.kbDocuments" />
              <div class="dashboard-view__stat-hint">点击管理知识库</div>
            </a-card>
          </a-col>
        </a-row>

        <a-card title="快捷入口" class="dashboard-view__quick-links">
          <a-space wrap :size="12">
            <a-button @click="router.push('/admin/departments')">
              <ApartmentOutlined /> 部门管理
            </a-button>
            <a-button @click="router.push('/admin/users')">
              <TeamOutlined /> 用户管理
            </a-button>
            <a-button @click="router.push('/admin/llm')">
              <CloudOutlined /> LLM 配置
            </a-button>
            <a-button @click="router.push('/admin/skills')">
              <ThunderboltOutlined /> Skill 管理
            </a-button>
            <a-button @click="router.push('/admin/kb')">
              <BookOutlined /> 知识库
            </a-button>
            <a-button @click="router.push('/admin/usage')">
              <BarChartOutlined /> 用量仪表盘
            </a-button>
          </a-space>
        </a-card>

        <a-card title="LLM 提供商" class="dashboard-view__providers">
          <a-empty v-if="providers.length === 0" description="暂无 LLM 提供商" />
          <a-list v-else size="small" :data-source="providers" :bordered="false">
            <template #renderItem="{ item }">
              <a-list-item>
                <a-list-item-meta :title="item.name" :description="`${item.type} · ${formatModels(item)}`" />
              </a-list-item>
            </template>
          </a-list>
        </a-card>
      </div>
    </a-spin>
  </div>
</template>

<script setup lang="ts">
/**
 * Admin dashboard — overview cards + quick links.
 *
 * Loads counts for departments, users, skills, KB documents, and the
 * list of LLM providers in parallel on mount. Each stat card links to
 * the corresponding management page.
 */
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  ApartmentOutlined,
  TeamOutlined,
  CloudOutlined,
  ThunderboltOutlined,
  BookOutlined,
  BarChartOutlined,
} from '@ant-design/icons-vue'
import { adminApi, type ILlmProvider } from '@/api/admin'

const router = useRouter()

const loading = ref(false)
const stats = reactive({
  departments: 0,
  users: 0,
  skills: 0,
  kbDocuments: 0,
})
const providers = ref<ILlmProvider[]>([])

function formatModels(p: ILlmProvider): string {
  const keys = Object.keys(p.models ?? {})
  return keys.length ? keys.join(', ') : '—'
}

function extractMessage(err: unknown, fallback: string): string {
  if (err && typeof err === 'object') {
    const obj = err as { detail?: unknown; message?: unknown }
    if (typeof obj.detail === 'string' && obj.detail) return obj.detail
    if (typeof obj.message === 'string' && obj.message) return obj.message
  }
  return fallback
}

async function loadDashboard(): Promise<void> {
  loading.value = true
  const tasks: Promise<void>[] = [
    adminApi
      .listDepartments()
      .then((d) => {
        stats.departments = d.length
      })
      .catch((err) => {
        message.error(extractMessage(err, '加载部门列表失败'))
      }),
    adminApi
      .listUsers()
      .then((u) => {
        stats.users = u.length
      })
      .catch((err) => {
        message.error(extractMessage(err, '加载用户列表失败'))
      }),
    adminApi
      .listKbDocuments()
      .then((docs) => {
        stats.kbDocuments = docs.length
      })
      .catch((err) => {
        message.error(extractMessage(err, '加载 KB 文档失败'))
      }),
    adminApi
      .listLlmProviders()
      .then((p) => {
        providers.value = p
      })
      .catch((err) => {
        message.error(extractMessage(err, '加载 LLM 提供商失败'))
      }),
  ]
  // Skills count is best-effort — the admin API doesn't expose a list
  // endpoint, so we leave it at 0 unless we can derive it elsewhere.
  await Promise.all(tasks)
  loading.value = false
}

onMounted(() => {
  loadDashboard()
})
</script>

<style scoped>
.dashboard-view {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.dashboard-view__header {
  margin-bottom: 16px;
}

.dashboard-view__body {
  display: flex;
  flex-direction: column;
  gap: var(--space-4);
}

.dashboard-view__stat-card {
  cursor: pointer;
  transition: all var(--transition-fast);
}

.dashboard-view__stat-card:hover {
  border-color: var(--border-color-active);
}

.dashboard-view__stat-hint {
  margin-top: var(--space-2);
  font-size: var(--font-xs);
  color: var(--text-tertiary);
}

.dashboard-view__quick-links {
  margin-top: var(--space-4);
}

.dashboard-view__providers {
  margin-top: 0;
}
</style>
