<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import DataTablePage from '@/components/DataTablePage.vue'
import ModelStatusTag from '@/components/ModelStatusTag.vue'
import { usePolling } from '@/composables/usePolling'
import {
  getEvalList,
  deleteEval,
} from '@/api/modules/eval'
import type { EvalTask } from '@/types'

const router = useRouter()
const activeTab = ref('tasks')

const evalLoading = ref(false)
const evalList = ref<EvalTask[]>([])

// 排行榜（原项目为 mock 数据）
const leaderboard = ref([
  { rank: 1, name: 'GPT-4', score: 92.5 },
  { rank: 2, name: 'Claude-3', score: 90.1 },
  { rank: 3, name: 'Qwen-Max', score: 85.3 },
])

const ACTIVE_STATUSES = new Set(['pending', 'queued', 'running'])

async function loadEvalList(options: { silent?: boolean } = {}) {
  if (!options.silent) evalLoading.value = true
  try {
    evalList.value = (await getEvalList()) || []
  } catch {
    evalList.value = []
  } finally {
    if (!options.silent) evalLoading.value = false
  }
}

async function handleDeleteEval(row: any) {
  await ElMessageBox.confirm('确定要删除这个评测任务吗？', '确认删除', { type: 'warning' })
  await deleteEval(row.id)
  evalList.value = evalList.value.filter((item) => item.id !== row.id)
  ElMessage.success('删除成功')
  await loadEvalList()
}

function handleCreateClick() {
  router.push('/model-eval/create')
}

function isActiveTab(tab: string) {
  return activeTab.value === tab
}

function handleViewDetail(row: any) {
  router.push({ name: 'model-eval-detail', params: { id: row.id } })
}

const { start: startPolling, stop: stopPolling } = usePolling(
  async () => {
    await loadEvalList({ silent: true })
    if (!evalList.value.some((item) => ACTIVE_STATUSES.has(String(item.status || '')))) {
      stopPolling()
    }
  },
  5000,
  { immediate: false },
)

onMounted(async () => {
  await loadEvalList()
  if (evalList.value.some((item) => ACTIVE_STATUSES.has(String(item.status || '')))) {
    startPolling()
  }
})

onUnmounted(() => {
  stopPolling()
})
</script>

<template>
  <div class="eval-page">
    <!-- 评测任务 -->
    <DataTablePage
      v-if="activeTab === 'tasks'"
      title=""
      :data="evalList"
      :loading="evalLoading"
      :delete-fn="handleDeleteEval"
      create-text="创建评测任务"
      @create="handleCreateClick"
      row-key="id"
      @refresh="loadEvalList"
    >
      <template #title>
        <div class="capsule-tabs">
          <button class="capsule-tab-item" :class="{ active: isActiveTab('tasks') }" @click="activeTab = 'tasks'">评测任务</button>
          <button class="capsule-tab-item" :class="{ active: isActiveTab('leaderboard') }" @click="activeTab = 'leaderboard'">排行榜</button>
        </div>
      </template>
            <template #columns>
              <el-table-column label="任务名称" prop="eval_task_name" align="center" />
              <el-table-column label="评测模型" prop="model_name" align="center" />
              <el-table-column label="数据集" prop="dataset" align="center" />
              <el-table-column label="指标" prop="metric" align="center" />
              <el-table-column label="评分" prop="score" width="100" align="center" />
              <el-table-column label="状态" width="100" align="center">
                <template #default="{ row }">
                  <ModelStatusTag :status="row.status" />
                </template>
              </el-table-column>
              <el-table-column label="创建时间" align="center" width="180">
                <template #default="{ row }">
                  {{ row.create_time ? new Date(row.create_time).toLocaleString('zh-CN') : '-' }}
                </template>
              </el-table-column>
            </template>
            <template #actions="{ row }">
              <el-button link type="primary" size="small" @click="handleViewDetail(row)">
                <i class="fa fa-file-text-o" style="margin-right: 4px" />详情
              </el-button>
              <el-button link type="danger" size="small" @click="handleDeleteEval(row)">
                <i class="fa fa-trash-o" style="margin-right: 4px" />删除
              </el-button>
            </template>
    </DataTablePage>

    <!-- 排行榜 -->
    <DataTablePage 
      v-if="activeTab === 'leaderboard'"
      title="" 
      :data="leaderboard" 
      row-key="rank"
    >
      <template #title>
        <div class="capsule-tabs">
          <button class="capsule-tab-item" :class="{ active: isActiveTab('tasks') }" @click="activeTab = 'tasks'">评测任务</button>
          <button class="capsule-tab-item" :class="{ active: isActiveTab('leaderboard') }" @click="activeTab = 'leaderboard'">排行榜</button>
        </div>
      </template>
      <template #columns>
        <el-table-column label="排名" prop="rank" width="80" align="center" />
        <el-table-column label="模型名称" prop="name" align="center" />
        <el-table-column label="综合评分" prop="score" align="center" />
      </template>
    </DataTablePage>

  </div>
</template>

<style scoped lang="scss">
.eval-page {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

/* 胶囊切换栏样式 */
.capsule-tabs {
  display: flex;
  background: #f1f5f9;
  padding: 3px;
  border-radius: 8px;
  gap: 2px;
  border: 1px solid #e2e8f0;
}

.capsule-tab-item {
  border: 0;
  background: transparent;
  padding: 6px 20px;
  font-size: 13px;
  font-weight: 500;
  color: #64748b;
  cursor: pointer;
  border-radius: 6px;
  transition: all 0.2s ease;
  outline: none;

  &:hover {
    color: #1e293b;
  }

  &.active {
    background: #fff;
    color: #4f46e5; /* Primary color */
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06), 0 1px 2px rgba(0, 0, 0, 0.04);
    font-weight: 600;
  }
}

</style>
