<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 { Textarea } from '@/components/ui/textarea'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'

const cfg = reactive({
  url: 'http://localhost:8000/api/chat',
  total: 20,
  concurrent: 5,
  questions: `Tôi muốn mua áo đi làm
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?`,
})

const running = ref(false)
const stats = ref(null)
const results = ref([])
const alertMsg = ref('')

async function runStress() {
  const questions = cfg.questions.split('\n').map(q => q.trim()).filter(q => q)
  if (!cfg.url || !questions.length) return
  running.value = true; stats.value = null; results.value = []; alertMsg.value = ''

  try {
    const r = await fetch('/api/stress-test/run', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ target_url: cfg.url, total: cfg.total, concurrent: cfg.concurrent, questions })
    })
    const d = await r.json()
    if (d.status === 'success') { stats.value = d.stats; results.value = d.results || [] }
    else alertMsg.value = 'Lỗi: ' + d.message
  } catch (e) { alertMsg.value = 'Lỗi kết nối: ' + e.message }
  finally { running.value = false }
}

const latencyColor = ms => ms > 5000 ? 'text-destructive font-bold' : ms > 2000 ? 'text-amber-500 font-bold' : 'text-emerald-500 font-bold'
const errorRateColor = r => r > 0 ? 'destructive' : 'secondary'
</script>

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

      <!-- Header -->
      <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
        <div>
          <h1 class="text-3xl font-bold tracking-tight text-foreground">Stress Test</h1>
          <p class="text-sm text-muted-foreground mt-1">Bắn đồng thời hàng loạt request để đo throughput và latency</p>
        </div>
        <div class="flex items-center gap-3">
          <Badge v-if="running" variant="default" class="px-3 py-1.5 gap-2 text-sm">
            <span class="w-2 h-2 rounded-full bg-primary-foreground animate-ping inline-flex"></span>
            Đang chạy...
          </Badge>
          <Badge v-else-if="stats" variant="outline" class="px-3 py-1.5 gap-1.5 text-sm text-emerald-600 border-emerald-200 bg-emerald-50">
            <span class="w-2 h-2 rounded-full bg-emerald-500 inline-flex"></span>
            Hoàn thành
          </Badge>
        </div>
      </div>

      <!-- Alert -->
      <div v-if="alertMsg"
           class="bg-destructive/10 text-destructive border border-destructive/20 rounded-xl px-4 py-3 text-sm font-medium flex items-center gap-2">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="shrink-0"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
        {{ alertMsg }}
      </div>

      <!-- Config Card -->
      <Card class="border-border">
        <CardHeader class="pb-4 border-b border-border">
          <CardTitle class="text-base flex items-center gap-2">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>
            Cấu hình Stress Test
          </CardTitle>
        </CardHeader>
        <CardContent class="p-6">
          <div class="grid grid-cols-1 md:grid-cols-3 gap-5">

            <!-- URL -->
            <div class="md:col-span-3 space-y-1.5">
              <Label class="text-xs font-semibold text-muted-foreground uppercase tracking-wider">Target URL</Label>
              <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"><circle cx="12" cy="12" r="10"/><line x1="2" x2="22" y1="12" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
                <Input v-model="cfg.url" class="pl-9 font-mono text-sm h-10" />
              </div>
            </div>

            <!-- Total -->
            <div class="space-y-1.5">
              <Label class="text-xs font-semibold text-muted-foreground uppercase tracking-wider">Tổng Requests</Label>
              <Input v-model.number="cfg.total" type="number" min="1" max="1000" class="h-10 tabular-nums font-mono" />
            </div>

            <!-- Concurrent -->
            <div class="space-y-1.5">
              <Label class="text-xs font-semibold text-muted-foreground uppercase tracking-wider">Concurrent</Label>
              <Input v-model.number="cfg.concurrent" type="number" min="1" max="50" class="h-10 tabular-nums font-mono" />
            </div>

            <!-- Run button -->
            <div class="flex items-end">
              <Button @click="runStress"
                      :disabled="running"
                      class="w-full h-10 gap-2 text-sm font-bold"
                      variant="destructive">
                <span v-if="running" class="w-4 h-4 border-2 border-destructive-foreground border-t-transparent animate-spin rounded-full"></span>
                <svg v-else xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13 2 3 14h9l-1 8 10-12h-9l1-8z"/></svg>
                {{ running ? 'Đang bắn...' : 'BẮN TEST' }}
              </Button>
            </div>

            <!-- Questions textarea -->
            <div class="md:col-span-3 space-y-1.5">
              <Label class="text-xs font-semibold text-muted-foreground uppercase tracking-wider">
                Câu hỏi Test <span class="text-muted-foreground font-normal normal-case tracking-normal">(mỗi dòng 1 câu, random pick)</span>
              </Label>
              <Textarea v-model="cfg.questions" rows="6" class="font-mono text-sm resize-none leading-relaxed" />
            </div>
          </div>
        </CardContent>
      </Card>

      <!-- Running indicator -->
      <div v-if="running" class="flex items-center gap-4 bg-primary/5 border border-primary/10 rounded-xl px-5 py-4">
        <div class="w-5 h-5 border-2 border-primary border-t-transparent rounded-full animate-spin shrink-0"></div>
        <div>
          <p class="text-sm font-semibold text-foreground">Đang thực thi stress test...</p>
          <p class="text-xs text-muted-foreground mt-0.5">Bắn <span class="font-bold text-primary">{{ cfg.concurrent }}</span> request đồng thời — tổng <span class="font-bold text-primary">{{ cfg.total }}</span> requests</p>
        </div>
      </div>

      <!-- Stats Results -->
      <div v-if="stats" class="space-y-4">
        <div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
          <Card class="border-border">
            <CardContent class="p-5 text-center">
              <p class="text-4xl font-black text-foreground tabular-nums">{{ stats.total }}</p>
              <p class="text-xs font-semibold text-muted-foreground uppercase tracking-wider mt-2">Total Requests</p>
            </CardContent>
          </Card>

          <Card class="border-border">
            <CardContent class="p-5 text-center">
              <p class="text-4xl font-black text-primary tabular-nums">{{ stats.rps }}</p>
              <p class="text-xs font-semibold text-muted-foreground uppercase tracking-wider mt-2">Requests / sec</p>
            </CardContent>
          </Card>

          <Card :class="['border', stats.error_rate > 0 ? 'border-destructive/20 bg-destructive/5' : 'border-emerald-200 bg-emerald-50/30 dark:bg-emerald-900/10']">
            <CardContent class="p-5 text-center">
              <p :class="['text-4xl font-black tabular-nums', stats.error_rate > 0 ? 'text-destructive' : 'text-emerald-500']">{{ stats.error_rate }}%</p>
              <p class="text-xs font-semibold text-muted-foreground uppercase tracking-wider mt-2">Error Rate</p>
            </CardContent>
          </Card>

          <Card class="border-border">
            <CardContent class="p-5">
              <p class="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-3">Latency Stats</p>
              <div class="space-y-1.5">
                <div v-for="(label, key) in { avg_ms:'Avg', min_ms:'Min', max_ms:'Max', p95_ms:'P95' }" :key="key"
                     class="flex justify-between items-center text-xs">
                  <span class="text-muted-foreground">{{ label }}</span>
                  <span :class="['font-mono font-bold tabular-nums', stats[key] > 3000 ? 'text-destructive' : stats[key] > 1500 ? 'text-amber-500' : 'text-emerald-500']">
                    {{ stats[key] ? stats[key] + 'ms' : '—' }}
                  </span>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        <!-- Results Table -->
        <Card v-if="results.length" class="border-border overflow-hidden">
          <CardHeader class="pb-3 pt-4 px-5 border-b border-border bg-muted/10">
            <CardTitle class="text-sm flex items-center justify-between">
              <span>Per-Request Results</span>
              <Badge variant="secondary" class="font-mono">{{ results.length }} records</Badge>
            </CardTitle>
          </CardHeader>
          <CardContent class="p-0">
            <ScrollArea class="max-h-96 overflow-hidden">
              <Table>
                <TableHeader class="sticky top-0 bg-background/95 backdrop-blur">
                  <TableRow>
                    <TableHead class="w-12">#</TableHead>
                    <TableHead class="w-24">Latency</TableHead>
                    <TableHead class="w-20">Status</TableHead>
                    <TableHead>Question</TableHead>
                    <TableHead class="min-w-[200px]">Response Preview</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  <TableRow v-for="r in results" :key="r.id" class="group">
                    <TableCell class="font-mono text-xs text-muted-foreground">#{{ r.id }}</TableCell>
                    <TableCell>
                      <span :class="['font-mono text-xs', latencyColor(r.latency_ms)]">
                        {{ r.latency_ms || 0 }}ms
                      </span>
                    </TableCell>
                    <TableCell>
                      <Badge :variant="r.status === 'success' ? 'outline' : 'destructive'" class="text-[9px] uppercase tracking-wider">
                        {{ r.status === 'success' ? '200' : r.status_code || 'ERR' }}
                      </Badge>
                    </TableCell>
                    <TableCell class="text-sm text-foreground max-w-[200px] truncate">{{ r.question }}</TableCell>
                    <TableCell class="font-mono text-xs text-muted-foreground max-w-[300px] truncate">{{ r.response_preview }}</TableCell>
                  </TableRow>
                </TableBody>
              </Table>
            </ScrollArea>
          </CardContent>
        </Card>
      </div>
    </div>
  </DashboardLayout>
</template>
