<template>
  <div class="page-container">
    <div class="page-header">
      <span class="page-title">Experience Library</span>
      <el-select v-model="topologyFilter" placeholder="Topology" style="width: 150px" clearable @change="loadExperience">
        <el-option label="SSSR" value="SSSR" />
        <el-option label="DRSS" value="DRSS" />
      </el-select>
    </div>

    <div class="card">
      <el-table :data="cases" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="topology" label="Topology" width="90">
          <template #default="{ row }">
            <el-tag size="small">{{ row.topology }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="source_plan_id" label="Source Plan" width="180" />
        <el-table-column label="Params" min-width="200">
          <template #default="{ row }">
            <span v-for="(v, k) in row.params" :key="k" style="margin-right: 12px; font-size: 12px">
              {{ k }}={{ v }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="Key Metrics" min-width="250">
          <template #default="{ row }">
            <span style="font-size: 12px; color: #6b7280">
              Tavg={{ row.metrics?.tavg_nm?.toFixed(3) }}Nm,
              Eff={{ row.metrics?.efficiency_pct?.toFixed(1) }}%,
              Ripple={{ row.metrics?.ripple_pct?.toFixed(2) }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="conclusion" label="Conclusion" min-width="200" show-overflow-tooltip />
        <el-table-column prop="rating" label="Rating" width="80">
          <template #default="{ row }">
            <el-rate v-model="row.rating" disabled size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="Created" width="160">
          <template #default="{ row }">{{ formatDate(row.created_at) }}</template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { experienceApi } from '@/api'

const loading = ref(false)
const cases = ref<any[]>([])
const topologyFilter = ref('')

async function loadExperience() {
  loading.value = true
  try {
    const params: any = { limit: 100 }
    if (topologyFilter.value) params.topology = topologyFilter.value
    const res = await experienceApi.list(params)
    cases.value = res.data.items
  } catch (e: any) {
    ElMessage.error('Failed to load experience: ' + e.message)
  } finally {
    loading.value = false
  }
}

function formatDate(d: string) {
  return new Date(d).toLocaleString()
}

onMounted(loadExperience)
</script>
