<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import DashboardLayout from '../layouts/DashboardLayout.vue'
import { Input } from '@/components/ui/input'
import { Card, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { ScrollArea } from '@/components/ui/scroll-area'

const allRows     = ref([])
const loading     = ref(false)
const searchQ     = ref('')
const filter      = ref('all')   // all | human | ai
const limitSelect = ref('200')
const lastRefresh = ref('')
const modalRow    = ref(null)
let refreshTimer  = null

async function loadData() {
  loading.value = true
  try {
    const r = await fetch(`/api/lead/dashboard?limit=${limitSelect.value}`)
    const d = await r.json()
    allRows.value = d.data || []
    lastRefresh.value = new Date().toLocaleTimeString('vi-VN')
  } catch (e) {
    allRows.value = []
  } finally { loading.value = false }
}

const stats = computed(() => {
  const rows = allRows.value
  return {
    total:   rows.length,
    convs:   new Set(rows.map(r => r.conv_id)).size,
    devices: new Set(rows.map(r => r.device_id)).size,
    ai:      rows.filter(r => !r.is_human).length,
  }
})

const filtered = computed(() => {
  let rows = allRows.value
  if (filter.value === 'human') rows = rows.filter(r => r.is_human)
  if (filter.value === 'ai')    rows = rows.filter(r => !r.is_human)
  const q = searchQ.value.toLowerCase()
  if (q) rows = rows.filter(r =>
    (r.message || '').toLowerCase().includes(q) ||
    (r.conv_id  || '').toLowerCase().includes(q) ||
    (r.device_id || '').toLowerCase().includes(q)
  )
  return rows
})

function parseAIRow(row) {
  let text = row.message || '', products = 0, stage = '—'
  try {
    const p = JSON.parse(text)
    text = p.ai_response || text
    products = Array.isArray(p.products) ? p.products.length : 0
    const ls = p.lead_stage || {}
    stage = ls.stage_name || ls.stage || (typeof ls === 'string' ? ls : '—')
  } catch (_) {}
  return { text, products, stage }
}

function tsFormat(ts) {
  if (!ts) return '—'
  return new Date(ts).toLocaleString('vi-VN', { month:'2-digit', day:'2-digit', hour:'2-digit', minute:'2-digit' })
}

function filterByConv(convId) { searchQ.value = convId }

function showDetail(row) {
  let content = row.message || ''
  try { const p = JSON.parse(content); content = JSON.stringify(p, null, 2) } catch (_) {}
  modalRow.value = { ...row, formatted: content }
}

onMounted(() => {
  loadData()
  refreshTimer = setInterval(loadData, 30000)
})
onUnmounted(() => clearInterval(refreshTimer))
</script>

<template>
  <DashboardLayout>
    <div class="h-[calc(100vh-theme(spacing.16))] flex flex-col p-6 max-w-[1600px] mx-auto gap-6">
      
      <!-- Header Area -->
      <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 shrink-0">
        <div>
          <h1 class="text-2xl font-bold tracking-tight text-foreground">Lead History</h1>
          <div class="flex items-center gap-2 mt-1">
            <span class="relative flex h-2 w-2">
              <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
              <span class="relative inline-flex rounded-full h-2 w-2 bg-emerald-500"></span>
            </span>
            <p class="text-xs text-muted-foreground">Auto-refresh 30s · Cập nhật lúc {{ lastRefresh || '--:--' }}</p>
          </div>
        </div>
        
        <div class="flex items-center gap-3">
          <Select v-model="limitSelect" @update:modelValue="loadData">
            <SelectTrigger class="w-[130px] h-9">
              <SelectValue placeholder="Số dòng" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="50">50 dòng</SelectItem>
              <SelectItem value="100">100 dòng</SelectItem>
              <SelectItem value="200">200 dòng</SelectItem>
              <SelectItem value="500">500 dòng</SelectItem>
            </SelectContent>
          </Select>
          <Button variant="outline" size="sm" class="h-9 gap-2" @click="loadData">
            <span :class="{ 'animate-spin': loading }">↻</span> Refresh
          </Button>
        </div>
      </div>

      <!-- Stats Grid -->
      <div class="grid grid-cols-2 lg:grid-cols-4 gap-4 shrink-0">
        <Card v-for="(val, label) in { 'Tổng tin nhắn': stats.total, 'Lượt hội thoại': stats.convs, 'Số thiết bị': stats.devices, 'Bot phản hồi': stats.ai }" :key="label" class="bg-card shadow-sm border-border">
          <CardContent class="p-5 flex flex-col justify-center">
            <p class="text-3xl font-black text-foreground tabular-nums tracking-tight">{{ val }}</p>
            <p class="text-xs font-semibold text-muted-foreground uppercase tracking-wider mt-1">{{ label }}</p>
          </CardContent>
        </Card>
      </div>

      <!-- Main Content / Table Area -->
      <Card class="flex-1 flex flex-col overflow-hidden shadow-sm border-border">
        <!-- Controls Header -->
        <div class="p-4 border-b border-border bg-muted/20 flex flex-wrap items-center gap-3 shrink-0">
          <div class="relative w-full max-w-sm">
            <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="searchQ" placeholder="Tìm ID, thiết bị, đoạn chat..." class="pl-9 h-9 w-full shadow-none" />
          </div>

          <div class="flex bg-muted/50 p-1 rounded-md border border-border">
            <button v-for="(label, f) in { all:'Tất cả', human:'👤 User', ai:'🤖 Bot' }" :key="f"
                    @click="filter = f"
                    :class="['text-xs px-4 py-1.5 rounded-sm font-medium transition-all',
                              filter === f ? 'bg-background text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground']">
              {{ label }}
            </button>
          </div>

          <span class="text-xs text-muted-foreground font-medium ml-auto px-2">{{ filtered.length }} bản ghi hiển thị</span>
        </div>

        <!-- Scrollable Table -->
        <div class="flex-1 relative overflow-hidden bg-background">
          <div v-if="loading && !allRows.length" class="absolute inset-0 flex flex-col items-center justify-center z-10 bg-background/50 backdrop-blur-sm">
            <div class="w-6 h-6 border-2 border-primary border-t-transparent animate-spin rounded-full mb-3"></div>
            <p class="text-sm font-medium text-foreground">Đang tải dữ liệu...</p>
          </div>
          
          <div v-else-if="!filtered.length" class="absolute inset-0 flex flex-col items-center justify-center z-10 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"><rect width="20" height="16" x="2" y="4" rx="2"/><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/></svg>
            <p class="text-sm font-medium text-foreground">Không có dữ liệu phù hợp</p>
          </div>
          
          <ScrollArea class="h-full" v-else>
            <Table>
              <TableHeader class="sticky top-0 bg-background/95 backdrop-blur z-10 shadow-sm">
                <TableRow>
                  <TableHead class="w-16">ID</TableHead>
                  <TableHead class="w-24">Role</TableHead>
                  <TableHead class="w-32">Conv ID</TableHead>
                  <TableHead class="w-28">Device</TableHead>
                  <TableHead class="min-w-[300px]">Nội dung Chat</TableHead>
                  <TableHead class="w-24 text-center">Products</TableHead>
                  <TableHead class="w-40 text-center">Stage</TableHead>
                  <TableHead class="w-32 text-right">Thời gian</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                <TableRow v-for="row in filtered" :key="row.id" class="group">
                  <TableCell class="font-mono text-xs text-muted-foreground">#{{ row.id }}</TableCell>
                  
                  <TableCell>
                    <Badge :variant="row.is_human ? 'default' : 'secondary'" class="text-[10px] uppercase font-bold tracking-wider rounded-sm px-1.5">
                      {{ row.is_human ? '👤 User' : '🤖 Bot' }}
                    </Badge>
                  </TableCell>
                  
                  <TableCell>
                    <span class="font-mono text-xs text-primary hover:underline cursor-pointer bg-primary/5 px-1.5 py-0.5 rounded transition-colors"
                          @click="filterByConv(row.conv_id)" :title="row.conv_id">
                      {{ (row.conv_id || '').slice(0, 8) }}…
                    </span>
                  </TableCell>
                  
                  <TableCell>
                    <span class="font-mono text-[10px] text-muted-foreground" :title="row.device_id">
                      …{{ (row.device_id || '').slice(-8) }}
                    </span>
                  </TableCell>
                  
                  <TableCell class="max-w-md">
                    <div class="truncate text-sm text-foreground/90 cursor-pointer hover:text-primary transition-colors flex items-center pr-4"
                         @click="showDetail(row)">
                      {{ row.is_human ? (row.message || '').slice(0, 100) : parseAIRow(row).text.slice(0, 100) }}
                      <span v-if="(row.message || '').length > 100" class="text-muted-foreground shrink-0 ml-1">…</span>
                    </div>
                  </TableCell>
                  
                  <TableCell class="text-center">
                    <Badge v-if="!row.is_human && parseAIRow(row).products > 0" variant="outline" class="text-[10px] border-primary/20 bg-primary/5 text-primary">
                      {{ parseAIRow(row).products }} items
                    </Badge>
                    <span v-else class="text-muted-foreground/30">—</span>
                  </TableCell>
                  
                  <TableCell class="text-center">
                    <Badge v-if="!row.is_human && parseAIRow(row).stage !== '—'" variant="secondary" class="text-[10px] bg-emerald-500/10 text-emerald-600 hover:bg-emerald-500/20 truncate max-w-[120px]">
                      {{ parseAIRow(row).stage }}
                    </Badge>
                    <span v-else class="text-muted-foreground/30">—</span>
                  </TableCell>
                  
                  <TableCell class="text-xs text-muted-foreground text-right tabular-nums">
                    {{ tsFormat(row.created_at) }}
                  </TableCell>
                </TableRow>
              </TableBody>
            </Table>
          </ScrollArea>
        </div>
      </Card>

      <!-- Raw Payload Detail Modal -->
      <div v-if="modalRow" class="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm p-4 animate-in fade-in duration-200"
           @click.self="modalRow = null">
        <Card class="w-full max-w-3xl max-h-[85vh] flex flex-col shadow-xl border-border animate-in zoom-in-95 duration-200">
          <CardHeader class="border-b border-border py-4 px-6 flex flex-row items-center justify-between shrink-0 bg-muted/10">
            <div class="flex items-center gap-3">
              <Badge :variant="modalRow.is_human ? 'default' : 'secondary'">{{ modalRow.is_human ? '👤 User' : '🤖 Assistant' }}</Badge>
              <h3 class="text-sm font-semibold text-foreground">Message #{{ modalRow.id }}</h3>
            </div>
            <Button variant="ghost" size="icon" class="h-8 w-8 text-muted-foreground hover:text-destructive shrink-0 -mr-2" @click="modalRow = null">
              <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" 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>
          </CardHeader>
          <CardContent class="flex-1 p-0 overflow-hidden relative">
            <ScrollArea class="h-full">
              <div class="p-6">
                <!-- If AI, highlight the lead stage context first if exists -->
                <div v-if="!modalRow.is_human && parseAIRow(modalRow).stage !== '—'" class="mb-6 bg-accent/50 border border-border rounded-lg p-4">
                  <p class="text-xs font-bold uppercase tracking-wider text-muted-foreground mb-2">Thông tin Agent Trích xuất</p>
                  <div class="flex flex-wrap gap-2">
                    <Badge variant="secondary" class="bg-background">Stage: {{ parseAIRow(modalRow).stage }}</Badge>
                    <Badge variant="outline" class="bg-background">Sản phẩm ghim: {{ parseAIRow(modalRow).products }}</Badge>
                  </div>
                </div>
                
                <p class="text-xs font-bold uppercase tracking-wider text-muted-foreground mb-3">Raw JSON Payload</p>
                <div class="bg-[#1e1e1e] rounded-xl overflow-hidden shadow-inner border border-primary/10">
                  <pre class="p-5 text-[13px] text-green-400 font-mono leading-relaxed whitespace-pre-wrap">{{ modalRow.formatted }}</pre>
                </div>
              </div>
            </ScrollArea>
          </CardContent>
        </Card>
      </div>

    </div>
  </DashboardLayout>
</template>
