<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import DashboardLayout from '../layouts/DashboardLayout.vue'
import { Card, CardContent, CardHeader, CardTitle, CardFooter } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Textarea } from '@/components/ui/textarea'

const router = useRouter()
const experiments = ref([])
const tags = ref({})
const activity = ref({})
const loading = ref(true)
const searchTerm = ref('')
const currentTag = ref('')
const currentStatus = ref('')
const showModal = ref(false)
const saving = ref(false)
const form = ref({ version: '', title: '', content: '', model_name: '', tagsStr: '', score: '', status: 'draft' })

const statusVariant = { draft: 'secondary', running: 'default', done: 'outline', archived: 'secondary' }

const filtered = computed(() => {
  let f = experiments.value
  if (searchTerm.value) {
    const s = searchTerm.value.toLowerCase()
    f = f.filter(e => e.title.toLowerCase().includes(s) || (e.version||'').toLowerCase().includes(s) || (e.content || '').toLowerCase().includes(s))
  }
  return f
})

async function load() {
  loading.value = true
  let url = '/api/dashboard/experiments?'
  if (currentTag.value) url += `tag=${currentTag.value}&`
  if (currentStatus.value) url += `status=${currentStatus.value}&`
  try {
    const r = await fetch(url)
    const d = await r.json()
    experiments.value = d.experiments || []
    tags.value = d.tags || {}
    activity.value = d.activity || {}
  } finally { loading.value = false }
}

async function addExperiment() {
  if (!form.value.version || !form.value.title) return
  saving.value = true
  try {
    const tagsArr = form.value.tagsStr ? form.value.tagsStr.split(',').map(t => t.trim()) : []
    const body = {
      version: form.value.version, title: form.value.title,
      content: form.value.content, model_name: form.value.model_name,
      tags: tagsArr, status: form.value.status
    }
    if (form.value.score) body.score = parseFloat(form.value.score)
    await fetch('/api/dashboard/experiments', {
      method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body)
    })
    showModal.value = false
    form.value = { version: '', title: '', content: '', model_name: '', tagsStr: '', score: '', status: 'draft' }
    await load()
  } finally { saving.value = false }
}

async function pinExp(id) { await fetch(`/api/dashboard/experiments/${id}/pin`, { method: 'PATCH' }); load() }
async function deleteExp(id, title) {
  if (!confirm(`Xóa "${title}"?`)) return
  await fetch(`/api/dashboard/experiments/${id}`, { method: 'DELETE' })
  load()
}

function scoreColor(s) {
  if (s >= 8) return 'text-emerald-500'
  if (s >= 6) return 'text-primary'
  return 'text-destructive'
}

onMounted(load)
</script>

<template>
  <DashboardLayout>
    <div class="p-6 md:p-8 max-w-[1400px] mx-auto min-h-screen flex flex-col gap-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">Experiment Log</h1>
          <p class="text-sm text-muted-foreground mt-1">Theo dõi, đánh giá và lưu trữ các thử nghiệm LLM workflow</p>
        </div>
        <Button @click="showModal = true" class="shadow-sm 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="M5 12h14"/><path d="M12 5v14"/></svg>
          New Experiment
        </Button>
      </div>

      <Separator />

      <!-- Controls Row -->
      <div class="flex flex-col md:flex-row gap-4 items-start md:items-center justify-between bg-muted/20 p-4 rounded-xl border border-border">
        
        <!-- Search and Status -->
        <div class="flex flex-wrap items-center gap-3 w-full md:w-auto">
          <div class="relative max-w-sm w-full md:w-64">
            <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="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>
            <Input v-model="searchTerm" placeholder="Tìm tên, nội dung, version..." class="pl-9 h-9 w-full bg-background" />
          </div>

          <div class="flex bg-muted/50 p-1 rounded-md border border-border w-full md:w-auto overflow-x-auto shrink-0">
            <button v-for="s in ['', 'draft', 'running', 'done', 'archived']" :key="s"
              @click="currentStatus = s; load()"
              :class="['text-[11px] px-3 py-1.5 rounded-sm font-medium tracking-wide uppercase transition-all whitespace-nowrap',
                currentStatus === s ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground']">
              {{ s || 'All Status' }}
            </button>
          </div>
        </div>

        <!-- Tag Filters -->
        <div v-if="Object.keys(tags).length" class="flex gap-2 flex-wrap justify-start md:justify-end">
          <button @click="currentTag = ''; load()"
            :class="['text-[11px] px-2.5 py-1 rounded-full font-medium transition-colors border',
              !currentTag ? 'bg-foreground text-background border-foreground' : 'bg-background text-muted-foreground border-border hover:border-muted-foreground/30']">
            All Tags
          </button>
          <button v-for="(count, tag) in tags" :key="tag"
            @click="currentTag = currentTag === tag ? '' : tag; load()"
            :class="['text-[11px] px-2.5 py-1 rounded-full font-medium transition-colors border flex items-center gap-1.5',
              currentTag === tag ? 'bg-primary/10 text-primary border-primary/20' : 'bg-background text-muted-foreground border-border hover:border-muted-foreground/30']">
            #{{ tag }} <span :class="currentTag === tag ? 'opacity-80' : 'opacity-50'">{{ count }}</span>
          </button>
        </div>
      </div>

      <!-- Main Content Grid -->
      <div v-if="loading" class="flex flex-col items-center justify-center py-20 text-muted-foreground">
        <div class="w-8 h-8 border-2 border-primary border-t-transparent animate-spin rounded-full mb-4"></div>
        <p class="text-sm">Đang tải experiments...</p>
      </div>
      
      <div v-else-if="!filtered.length" class="flex flex-col items-center justify-center py-24 text-muted-foreground border border-dashed border-border rounded-xl bg-muted/10">
        <div class="text-5xl mb-4 opacity-30">🧪</div>
        <p class="text-base font-semibold text-foreground">Chưa có experiment nào phù hợp</p>
        <p class="text-sm mt-1">Thay đổi bộ lọc hoặc thêm thử nghiệm mới.</p>
      </div>
      
      <div v-else class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5">
        <Card v-for="exp in filtered" :key="exp.id"
              :class="['group flex flex-col hover:border-primary/30 transition-all hover:shadow-md',
                exp.pinned ? 'border-primary/40 bg-primary/5 line-[oklch(var(--primary))]' : 'border-border']">
          
          <!-- Card Header & Core Content -->
          <CardContent class="p-5 flex-1 flex flex-col">
            <div class="flex items-start justify-between mb-4">
              <div class="flex items-center gap-2 flex-wrap">
                <Badge variant="outline" class="font-mono text-xs px-2 bg-background shadow-sm">{{ exp.version }}</Badge>
                <Badge :variant="statusVariant[exp.status] || 'secondary'" class="text-[9px] uppercase px-1.5 tracking-wider">
                  {{ exp.status }}
                </Badge>
                <span v-if="exp.pinned" class="text-lg leading-none print-emoji" title="Pinned">📌</span>
              </div>
              
              <div class="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0 bg-background/50 backdrop-blur rounded p-1 border border-border">
                <button class="text-lg w-6 h-6 flex items-center justify-center hover:bg-muted rounded" @click="pinExp(exp.id)" title="Pin">📌</button>
                <button class="text-sm w-6 h-6 flex items-center justify-center hover:bg-destructive/10 text-destructive rounded" @click="deleteExp(exp.id, exp.title)" title="Delete">
                  <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>
            </div>

            <h3 class="font-bold text-lg text-foreground cursor-pointer hover:text-primary transition-colors leading-tight"
                @click="router.push('/experiment/' + exp.id)">
              {{ exp.title }}
            </h3>
            
            <p v-if="exp.content" class="text-sm text-muted-foreground mt-2 line-clamp-3 leading-relaxed flex-1">{{ exp.content }}</p>
            
            <div class="mt-4 flex items-center gap-2 text-[11px] text-muted-foreground bg-accent/50 p-2 rounded-md border border-border inline-flex w-max max-w-full truncate">
              <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" class="shrink-0"><path d="m12 14-8-4 8-4 8 4-8 4Z"/><path d="m12 14 8-4"/><path d="m12 22-8-4 8-4 8 4-8 4Z"/></svg>
              <span class="font-mono truncate">{{ exp.model_name || 'No model specified' }}</span>
            </div>

            <div v-if="exp.tags?.length" class="flex gap-1.5 flex-wrap mt-3">
              <Badge variant="secondary" v-for="t in exp.tags" :key="t" class="text-[10px] font-medium bg-muted hover:bg-muted/80">
                #{{ t }}
              </Badge>
            </div>
          </CardContent>

          <!-- Divider -->
          <div class="h-px bg-border w-full flex-none"></div>

          <!-- Bottom Metrics -->
          <div class="p-4 grid grid-flow-col auto-cols-fr gap-3 bg-card/50 rounded-b-xl">
            <div v-if="exp.score != null" class="flex flex-col justify-end text-center p-2 rounded-lg bg-background border border-border shadow-sm">
              <p :class="['text-xl font-black leading-none mb-1', scoreColor(exp.score)]">{{ exp.score }}</p>
              <p class="text-[9px] uppercase text-muted-foreground tracking-wider font-semibold">Score</p>
            </div>
            
            <div v-if="exp.latency_avg != null" class="flex flex-col justify-end text-center p-2 rounded-lg bg-background border border-border shadow-sm">
              <p :class="['text-lg font-bold leading-none mb-1', exp.latency_avg <= 1800 ? 'text-emerald-500' : 'text-destructive']">
                {{ exp.latency_avg }}<span class="text-xs font-normal opacity-70">ms</span>
              </p>
              <p class="text-[9px] uppercase text-muted-foreground tracking-wider font-semibold">Latency</p>
            </div>
            
            <div v-if="exp.cost_per_req != null" class="flex flex-col justify-end text-center p-2 rounded-lg bg-background border border-border shadow-sm">
              <p class="text-lg font-bold text-foreground leading-none mb-1"><span class="text-xs text-muted-foreground">$</span>{{ exp.cost_per_req }}</p>
              <p class="text-[9px] uppercase text-muted-foreground tracking-wider font-semibold">Cost/Req</p>
            </div>
            
            <div v-if="exp.error_rate != null" class="flex flex-col justify-end text-center p-2 rounded-lg bg-background border border-border shadow-sm">
              <p :class="['text-lg font-bold leading-none mb-1', exp.error_rate <= 1 ? 'text-emerald-500' : 'text-destructive']">
                {{ exp.error_rate }}<span class="text-xs">%</span>
              </p>
              <p class="text-[9px] uppercase text-muted-foreground tracking-wider font-semibold">Error</p>
            </div>
          </div>
          
          <div class="px-5 pb-3 text-right">
            <span class="text-[10px] text-muted-foreground/60 font-mono">{{ new Date(exp.created_at).toLocaleDateString('vi-VN') }}</span>
          </div>

        </Card>
      </div>
    </div>

    <!-- New Experiment Dialog -->
    <Dialog v-model:open="showModal">
      <DialogContent class="max-w-[550px] p-0 overflow-hidden gap-0 border-border">
        <DialogHeader class="px-6 py-4 border-b border-border bg-muted/20">
          <DialogTitle class="text-lg font-bold flex items-center gap-2 text-foreground">
            <span class="text-xl">🧪</span> New Experiment
          </DialogTitle>
        </DialogHeader>
        
        <div class="px-6 py-5 space-y-5">
          <div class="grid grid-cols-3 gap-4">
            <div class="col-span-1 space-y-1.5">
              <Label class="text-xs font-semibold text-foreground">Version *</Label>
              <Input v-model="form.version" placeholder="v2.3" class="h-9 font-mono text-sm" />
            </div>
            <div class="col-span-2 space-y-1.5">
              <Label class="text-xs font-semibold text-foreground">Status</Label>
              <Select v-model="form.status">
                <SelectTrigger class="h-9"><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="draft">Draft</SelectItem>
                  <SelectItem value="running">Running</SelectItem>
                  <SelectItem value="done">Done</SelectItem>
                  <SelectItem value="archived">Archived</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          
          <div class="space-y-1.5">
            <Label class="text-xs font-semibold text-foreground">Tên thử nghiệm *</Label>
            <Input v-model="form.title" placeholder="VD: Test Gemini Flash Lite với prompt v3" class="h-9 text-sm" />
          </div>
          
          <div class="space-y-1.5">
            <Label class="text-xs font-semibold text-foreground">Nội dung thay đổi</Label>
            <Textarea v-model="form.content" placeholder="- Bỏ system prompt cũ&#10;- Add few shot example" class="min-h-[100px] text-sm resize-none" />
          </div>
          
          <div class="space-y-1.5">
            <Label class="text-xs font-semibold text-foreground">LLM Model</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"><path d="m12 14-8-4 8-4 8 4-8 4Z"/><path d="m12 14 8-4"/><path d="m12 22-8-4 8-4 8 4-8 4Z"/></svg>
              <Input v-model="form.model_name" placeholder="gemini-3.1-flash-lite / claude-3-7-sonnet" class="h-9 pl-9 text-sm font-mono" />
            </div>
          </div>
          
          <div class="grid grid-cols-4 gap-4">
            <div class="col-span-3 space-y-1.5">
              <Label class="text-xs font-semibold text-foreground">Tags</Label>
              <Input v-model="form.tagsStr" placeholder="model, prompt, optimization... (cách nhau bằng phẩy)" class="h-9 text-sm" />
            </div>
            <div class="col-span-1 space-y-1.5">
              <Label class="text-xs font-semibold text-foreground">Score</Label>
              <Input v-model="form.score" type="number" step="0.1" min="0" max="10" placeholder="8.5" class="h-9 tabular-nums font-mono text-sm" />
            </div>
          </div>
        </div>
        
        <DialogFooter class="px-6 py-4 border-t border-border bg-muted/20 sm:justify-end gap-2">
          <Button variant="outline" @click="showModal = false" class="w-full sm:w-auto h-9">Hủy thao tác</Button>
          <Button @click="addExperiment" :disabled="saving || !form.version || !form.title" class="w-full sm:w-auto h-9">
            <span v-if="saving" class="w-4 h-4 border-2 border-primary-foreground border-t-transparent animate-spin rounded-full mr-2"></span>
            {{ saving ? 'Đang tạo...' : 'Tạo Experiment' }}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  </DashboardLayout>
</template>
