<script setup>
import { ref, reactive } from 'vue'
import DashboardLayout from '../layouts/DashboardLayout.vue'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Separator } from '@/components/ui/separator'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'

const STORAGE_KEY = 'regression_test_cases_vue'
const DEFAULT_CASES = [
  'Tôi muốn mua áo đi làm, không biết chọn màu gì?',
  'Shop có váy dự tiệc không?',
  'Ngân sách 500k mua được gì?',
  'Có áo polo nam size XL không?',
  'Giá áo khoác mùa đông bao nhiêu?',
  'Có chương trình khuyến mãi gì không?',
  'Giao hàng mất bao lâu?',
  'Chính sách đổi trả thế nào?',
  'Tôi muốn mua quần jeans nữ',
  'Size chart của Canifa như thế nào?',
]

const URL_PRESETS = [
  { label: 'Dev',    url: 'http://localhost:8000/api/chat' },
  { label: 'Prod',   url: 'https://api.canifa.vn/api/chat' },
  { label: 'Custom', url: '' },
]

function loadCases() {
  try { const s = localStorage.getItem(STORAGE_KEY); if (s) return JSON.parse(s) } catch (_) {}
  return DEFAULT_CASES.map((q, i) => ({ id: Date.now() + i, question: q }))
}

const testCases = ref(loadCases())
const results   = ref([])
const running   = ref(false)
const stopFlag  = ref(false)
const targetUrl = ref('http://localhost:8000/api/chat')
const activePreset = ref(0)
const progress  = reactive({ current: 0, total: 0, label: '' })
const expanded  = reactive({})

function save() { localStorage.setItem(STORAGE_KEY, JSON.stringify(testCases.value)) }

function addCase() {
  testCases.value.push({ id: Date.now(), question: '' })
  save()
}
function deleteCase(id) { testCases.value = testCases.value.filter(tc => tc.id !== id); save() }
function updateCase(id, val) { testCases.value = testCases.value.map(tc => tc.id === id ? { ...tc, question: val } : tc); save() }

function setPreset(idx, url) {
  activePreset.value = idx
  if (url) targetUrl.value = url
}

async function runAll() {
  if (running.value) return
  const valid = testCases.value.filter(tc => tc.question.trim())
  if (!valid.length) return
  running.value = true; stopFlag.value = false; results.value = []
  progress.total = valid.length

  for (let i = 0; i < valid.length; i++) {
    if (stopFlag.value) break
    const tc = valid[i]
    progress.current = i + 1
    progress.label   = `#${i + 1}: "${tc.question.slice(0, 45)}..."`

    try {
      const r = await fetch('/api/regression-test/run', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ target_url: targetUrl.value, test_cases: [{ id: tc.id, question: tc.question }], timeout: 60 })
      })
      const d = await r.json()
      if (d.results?.length) results.value.push(d.results[0])
      else throw new Error(d.message || 'No results')
    } catch (e) {
      results.value.push({ id: tc.id, question: tc.question, status: 'error', response: e.message, latency_ms: null })
    }
  }

  running.value = false; stopFlag.value = false
}

function stop() { stopFlag.value = true; running.value = false }
function toggleExpand(i) { expanded[i] = !expanded[i] }

const computeStats = () => {
  const ok   = results.value.filter(r => r.status === 'success').length
  const fail = results.value.filter(r => r.status === 'error').length
  const lats = results.value.filter(r => r.latency_ms).map(r => r.latency_ms)
  const avg  = lats.length ? Math.round(lats.reduce((s, v) => s + v, 0) / lats.length) : null
  return { ok, fail, avg, total: results.value.length }
}

function exportJSON() {
  const blob = new Blob([JSON.stringify(testCases.value, null, 2)], { type: 'application/json' })
  const a = document.createElement('a'); a.href = URL.createObjectURL(blob)
  a.download = `test-cases-${new Date().toISOString().slice(0, 10)}.json`; a.click()
}

function importJSON() {
  const input = document.createElement('input'); input.type = 'file'; input.accept = '.json'
  input.onchange = async e => {
    try {
      const text = await e.target.files[0].text()
      const data = JSON.parse(text)
      if (Array.isArray(data)) {
        testCases.value = data.map((item, i) => ({ id: Date.now() + i, question: typeof item === 'string' ? item : item.question || '' }))
        save()
      }
    } catch (_) {}
  }
  input.click()
}

const passRate = () => results.value.length ? Math.round(computeStats().ok / results.value.length * 100) : 0
</script>

<template>
  <DashboardLayout>
    <div class="p-6 md:p-8 max-w-[1400px] mx-auto min-h-screen">

      <!-- Header -->
      <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-6">
        <div>
          <h1 class="text-3xl font-bold tracking-tight text-foreground">Regression Test</h1>
          <p class="text-sm text-muted-foreground mt-1">Chạy hàng loạt câu hỏi vào chatbot và kiểm tra response chất lượng</p>
        </div>
        <div class="flex gap-2 shrink-0">
          <Button v-if="!running" size="sm" variant="outline" class="h-9 gap-2" @click="exportJSON">
            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/></svg>
            Export
          </Button>
          <Button v-if="!running" size="sm" variant="outline" class="h-9 gap-2" @click="importJSON">
            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" x2="12" y1="3" y2="15"/></svg>
            Import
          </Button>
          <Button v-if="!running" class="h-9 gap-2"
                  @click="runAll"
                  :disabled="!testCases.filter(t => t.question.trim()).length">
            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg>
            Run All ({{ testCases.filter(t => t.question.trim()).length }})
          </Button>
          <Button v-else variant="destructive" class="h-9 gap-2" @click="stop">
            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="6" width="12" height="12"/></svg>
            Stop
          </Button>
        </div>
      </div>

      <div class="grid grid-cols-1 xl:grid-cols-[1fr_420px] gap-5">

        <!-- ─── Left: Test Cases Config ─── -->
        <Card class="flex flex-col border-border">
          <CardHeader class="border-b border-border pb-3 pt-4 px-5">
            <CardTitle class="text-base flex items-center justify-between">
              <span>Test Cases <span class="text-muted-foreground font-normal text-sm ml-1">({{ testCases.length }})</span></span>
              <Button size="sm" variant="ghost" class="h-7 text-xs" @click="addCase">+ Thêm</Button>
            </CardTitle>
          </CardHeader>
          <CardContent class="p-5 space-y-5 flex-1 flex flex-col">

            <!-- Target URL selector -->
            <div class="space-y-2">
              <Label class="text-xs font-semibold text-muted-foreground uppercase tracking-wider">Target Endpoint</Label>
              <div class="flex bg-muted/50 p-1 rounded-md border border-border w-max">
                <button v-for="(p, i) in URL_PRESETS" :key="i"
                        @click="setPreset(i, p.url)"
                        :class="['text-[11px] px-4 py-1 rounded-sm font-semibold transition-all',
                                  activePreset === i ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground']">
                  {{ p.label }}
                </button>
              </div>
              <div class="relative">
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>
                <Input v-model="targetUrl" placeholder="https://..." class="h-9 pl-9 font-mono text-sm" />
              </div>
            </div>

            <!-- Progress -->
            <div v-if="running" class="space-y-2 bg-primary/5 border border-primary/10 rounded-xl p-4">
              <div class="flex justify-between text-xs text-muted-foreground mb-1">
                <span class="truncate">{{ progress.label }}</span>
                <span class="font-bold text-foreground ml-3 shrink-0">{{ progress.current }}/{{ progress.total }}</span>
              </div>
              <div class="h-2 bg-muted rounded-full overflow-hidden">
                <div class="h-full bg-primary rounded-full transition-all duration-500 ease-out"
                     :style="{ width: (progress.current / progress.total * 100) + '%' }"></div>
              </div>
            </div>

            <!-- Cases list -->
            <ScrollArea class="flex-1 max-h-[380px] pr-1">
              <div class="space-y-1.5">
                <div v-for="(tc, i) in testCases" :key="tc.id"
                     class="flex items-center gap-2.5 group">
                  <span class="text-[10px] text-muted-foreground/50 font-mono w-5 shrink-0 text-center select-none">{{ i + 1 }}</span>
                  <input :value="tc.question"
                         @change="updateCase(tc.id, $event.target.value)"
                         placeholder="Nhập câu hỏi test..."
                         class="flex-1 text-sm border border-input rounded-md px-3 py-2 bg-background text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring transition-colors hover:border-border" />
                  <button @click="deleteCase(tc.id)"
                          class="w-7 h-7 flex items-center justify-center opacity-0 group-hover:opacity-100 hover:bg-destructive/10 hover:text-destructive text-muted-foreground rounded-md transition-all shrink-0">
                    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
                  </button>
                </div>

                <button @click="addCase"
                        class="w-full py-2.5 border border-dashed border-border rounded-xl text-xs text-muted-foreground hover:border-primary/40 hover:text-primary hover:bg-primary/5 transition-colors flex items-center justify-center gap-1.5">
                  <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="M12 5v14"/></svg>
                  Thêm test case
                </button>
              </div>
            </ScrollArea>
          </CardContent>
        </Card>

        <!-- ─── Right: Results Panel ─── -->
        <div class="space-y-4">

          <!-- Stats cards -->
          <div v-if="results.length > 0" class="grid grid-cols-2 gap-3">
            <Card class="border-border">
              <CardContent class="p-4 text-center">
                <p class="text-3xl font-black text-foreground tabular-nums">{{ computeStats().total }}</p>
                <p class="text-xs font-semibold text-muted-foreground uppercase tracking-wider mt-1">Tổng Test</p>
              </CardContent>
            </Card>
            <Card class="border-border">
              <CardContent class="p-4 text-center">
                <p class="text-3xl font-black tabular-nums" :class="passRate() >= 80 ? 'text-emerald-500' : passRate() >= 50 ? 'text-amber-500' : 'text-destructive'">{{ passRate() }}%</p>
                <p class="text-xs font-semibold text-muted-foreground uppercase tracking-wider mt-1">Pass Rate</p>
              </CardContent>
            </Card>
            <Card class="border-border">
              <CardContent class="p-4 text-center">
                <p class="text-3xl font-black text-emerald-500 tabular-nums">{{ computeStats().ok }}</p>
                <p class="text-xs font-semibold text-muted-foreground uppercase tracking-wider mt-1">Passed</p>
              </CardContent>
            </Card>
            <Card class="border-border">
              <CardContent class="p-4 text-center">
                <div>
                  <p class="text-3xl font-black tabular-nums" :class="computeStats().fail > 0 ? 'text-destructive' : 'text-muted-foreground'">{{ computeStats().fail }}</p>
                  <p class="text-xs font-semibold text-muted-foreground uppercase tracking-wider mt-1">Failed</p>
                </div>
              </CardContent>
            </Card>
          </div>

          <!-- Latency stat -->
          <Card v-if="results.length && computeStats().avg" class="border-border">
            <CardContent class="p-4 flex items-center justify-between">
              <div>
                <p class="text-xs font-semibold text-muted-foreground uppercase tracking-wider">Avg Latency</p>
              </div>
              <Badge variant="outline" class="font-mono text-sm px-3 py-1 bg-primary/5 border-primary/20 text-primary">
                {{ computeStats().avg }}ms
              </Badge>
            </CardContent>
          </Card>

          <!-- Empty state -->
          <Card v-if="!results.length" class="border-dashed border-border">
            <CardContent class="flex flex-col items-center justify-center py-16 text-muted-foreground">
              <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="opacity-20 mb-3"><path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/><path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"/><line x1="2" x2="22" y1="2" y2="22"/></svg>
              <p class="text-sm font-medium text-foreground">Chưa có kết quả</p>
              <p class="text-xs mt-1">Nhấn "Run All" để chạy toàn bộ test cases.</p>
            </CardContent>
          </Card>

          <!-- Results accordion list -->
          <Card v-else class="overflow-hidden border-border">
            <CardHeader class="pb-3 pt-4 px-5 border-b border-border">
              <CardTitle class="text-sm">Chi tiết Kết quả</CardTitle>
            </CardHeader>
            <CardContent class="p-0">
              <ScrollArea class="max-h-[480px]">
                <div class="divide-y divide-border">
                  <div v-for="(r, i) in results" :key="r.id">
                    <div @click="toggleExpand(i)"
                         :class="['flex items-center gap-3 px-4 py-3 cursor-pointer hover:bg-accent/30 transition-colors',
                           r.status === 'error' ? 'bg-destructive/5 hover:bg-destructive/10' : '']">
                      <div :class="['w-6 h-6 rounded-full flex items-center justify-center text-[9px] font-black shrink-0 border',
                                     r.status === 'success'
                                       ? 'bg-emerald-500/10 text-emerald-600 border-emerald-200'
                                       : 'bg-destructive/10 text-destructive border-destructive/20']">
                        {{ i + 1 }}
                      </div>
                      <p class="text-sm text-foreground flex-1 truncate">{{ r.question }}</p>
                      <div class="flex items-center gap-2 shrink-0">
                        <span v-if="r.latency_ms" class="text-[10px] text-muted-foreground font-mono">{{ Math.round(r.latency_ms) }}ms</span>
                        <Badge :variant="r.status === 'success' ? 'outline' : 'destructive'" class="text-[9px] uppercase tracking-wider py-0.5 px-1.5">
                          {{ r.status === 'success' ? 'PASS' : 'FAIL' }}
                        </Badge>
                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" :class="['text-muted-foreground/50 transition-transform', expanded[i] ? 'rotate-180' : '']"><path d="m6 9 6 6 6-6"/></svg>
                      </div>
                    </div>
                    <div v-if="expanded[i]" class="px-5 py-4 bg-muted/30 border-t border-border">
                      <p class="text-sm text-foreground leading-relaxed whitespace-pre-wrap">{{ r.response }}</p>
                      <p v-if="r.trace_id" class="text-[10px] text-muted-foreground font-mono mt-2 pt-2 border-t border-border">trace_id: {{ r.trace_id }}</p>
                    </div>
                  </div>
                </div>
              </ScrollArea>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  </DashboardLayout>
</template>
