<template>
  <div class="page-container" v-loading="loading">
    <div class="page-header">
      <div>
        <el-button text @click="goBack" style="padding: 0; margin-bottom: 8px">
          <el-icon><ArrowLeft /></el-icon> Back
        </el-button>
        <span class="page-title">{{ plan?.name }}</span>
        <el-tag size="small" type="primary" style="margin-left: 12px">{{ plan?.plan_id }}</el-tag>
        <el-tag size="small" :type="planStatusType(plan?.status)" style="margin-left: 8px">{{ plan?.status }}</el-tag>
      </div>
      <div>
        <el-button @click="downloadPlan">
          <el-icon><Download /></el-icon> Download JSON
        </el-button>
        <el-upload :show-file-list="false" :before-upload="uploadResults" accept=".csv">
          <el-button type="success">
            <el-icon><Upload /></el-icon> Upload Results
          </el-button>
        </el-upload>
      </div>
    </div>

    <el-row :gutter="16" v-if="plan">
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-label">Estimated Points</div>
          <div class="stat-value">{{ plan.estimated_points }}</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-label">Est. Time</div>
          <div class="stat-value">{{ plan.estimated_time_min }} min</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-label">Results Uploaded</div>
          <div class="stat-value">{{ results.length }}</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-label">OK / Failed</div>
          <div class="stat-value">{{ okCount }} / {{ failedCount }}</div>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="16" v-if="plan">
      <el-col :span="10">
        <div class="card">
          <h3 style="margin-bottom: 12px">Scan Variables</h3>
          <el-table :data="variablesList" size="small" border>
            <el-table-column prop="name" label="Variable" width="120" />
            <el-table-column prop="unit" label="Unit" width="70" />
            <el-table-column prop="count" label="Count" width="70" />
            <el-table-column prop="values" label="Values" />
          </el-table>
        </div>
      </el-col>
      <el-col :span="14">
        <div class="card">
          <h3 style="margin-bottom: 12px">Plan JSON</h3>
          <pre style="background: #f8fafc; padding: 12px; border-radius: 4px; font-size: 11px; max-height: 300px; overflow: auto">{{ JSON.stringify(plan.plan_data, null, 2) }}</pre>
        </div>
      </el-col>
    </el-row>

    <!-- Results Section -->
    <div class="card" v-if="results.length > 0">
      <h3 style="margin-bottom: 12px">Simulation Results</h3>
      <el-table :data="results" stripe border size="small" max-height="400">
        <el-table-column prop="run_index" label="#" width="50" fixed />
        <el-table-column v-for="param in paramKeys" :key="param" :label="param" :prop="`params.${param}`" width="100">
          <template #default="{ row }">{{ row.params[param] }}</template>
        </el-table-column>
        <el-table-column prop="metrics.tavg_nm" label="Tavg (Nm)" width="100">
          <template #default="{ row }">{{ row.metrics.tavg_nm?.toFixed(4) }}</template>
        </el-table-column>
        <el-table-column prop="metrics.ripple_pct" label="Ripple (%)" width="100">
          <template #default="{ row }">{{ row.metrics.ripple_pct?.toFixed(3) }}</template>
        </el-table-column>
        <el-table-column prop="metrics.efficiency_pct" label="Eff (%)" width="90">
          <template #default="{ row }">{{ row.metrics.efficiency_pct?.toFixed(2) }}</template>
        </el-table-column>
        <el-table-column prop="metrics.total_losses_w" label="Loss (W)" width="90">
          <template #default="{ row }">{{ row.metrics.total_losses_w?.toFixed(2) }}</template>
        </el-table-column>
        <el-table-column prop="metrics.copper_loss_w" label="Cu (W)" width="80" />
        <el-table-column prop="metrics.iron_loss_w" label="Fe (W)" width="80" />
        <el-table-column prop="metrics.back_emf_v" label="BEMF (V)" width="90" />
        <el-table-column prop="metrics.no_load_speed_rpm" label="NoLoad RPM" width="100" />
        <el-table-column prop="solve_time_s" label="Time (s)" width="80" />
        <el-table-column prop="status" label="Status" width="80">
          <template #default="{ row }">
            <el-tag size="small" :type="row.status === 'OK' ? 'success' : 'danger'">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-empty v-else description="No results uploaded yet. Upload scan_results.csv to see results." />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Download, Upload } from '@element-plus/icons-vue'
import { planApi } from '@/api'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const plan = ref<any>(null)
const results = ref<any[]>([])

const variablesList = computed(() => {
  if (!plan.value?.plan_data?.variables) return []
  return plan.value.plan_data.variables.map((v: any) => ({
    name: v.name,
    unit: v.unit || '',
    count: v.values?.length || 0,
    values: v.values?.join(', ') || ''
  }))
})

const paramKeys = computed(() => {
  if (results.value.length === 0) return []
  return Object.keys(results.value[0].params || {})
})

const okCount = computed(() => results.value.filter(r => r.status === 'OK').length)
const failedCount = computed(() => results.value.filter(r => r.status !== 'OK').length)

async function loadPlan() {
  loading.value = true
  try {
    const id = Number(route.params.id)
    const res = await planApi.get(id)
    plan.value = res.data
    const resultsRes = await planApi.getResults(id)
    results.value = resultsRes.data.items
  } catch (e: any) {
    ElMessage.error('Failed to load plan: ' + e.message)
  } finally {
    loading.value = false
  }
}

function downloadPlan() {
  const data = JSON.stringify(plan.value.plan_data, null, 2)
  const blob = new Blob([data], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${plan.value.plan_id}.json`
  a.click()
  URL.revokeObjectURL(url)
  ElMessage.success('Plan JSON downloaded')
}

async function uploadResults(file: File) {
  try {
    const id = Number(route.params.id)
    const res = await planApi.uploadResults(id, file)
    ElMessage.success(`Uploaded ${res.data.count} results`)
    await loadPlan()
  } catch (e: any) {
    ElMessage.error('Upload failed: ' + e.message)
  }
  return false
}

function goBack() {
  if (plan.value?.project_id) {
    router.push(`/projects/${plan.value.project_id}`)
  } else {
    router.push('/projects')
  }
}

function planStatusType(status: string) {
  const map: Record<string, string> = { draft: 'info', confirmed: 'warning', executing: 'primary', completed: 'success', failed: 'danger' }
  return map[status] || 'info'
}

onMounted(loadPlan)
</script>
