<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import DashboardLayout from '../layouts/DashboardLayout.vue'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { Separator } from '@/components/ui/separator'
import { Progress } from '@/components/ui/progress'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow
} from '@/components/ui/table'
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue
} from '@/components/ui/select'
import {
  Dialog, DialogContent, DialogHeader, DialogTitle
} from '@/components/ui/dialog'

const API = '/api/product-desc'
const PAGE_SIZE = 30

// ── State ──────────────────────────────────────────────────
const overview    = ref(null)
const lineFilters = ref([])
const products    = ref([])
const total       = ref(0)
const loading     = ref(false)
const loadingOverview = ref(true)
const currentPage = ref(0)

const filters = reactive({ search: '', status: '', line: '' })

// Detail
const detailOpen = ref(false)
const detailCode = ref(null)
const detailData = ref(null)
const detailTab  = ref('clean')
const detailName = ref('')

// Per-row loading
const rowLoading = reactive({})

// Toast
const toast = ref('')
let toastTimer = null

// Batch polling
let pollTimer = null

// ── Overview ──────────────────────────────────────────────
async function loadOverview() {
  loadingOverview.value = true
  try {
    const d = await fetch(`${API}/overview`).then(r => r.json())
    if (d.status !== 'success') return
    overview.value = d
  } catch (_) {}
  finally { loadingOverview.value = false }
}

// ── Filters ───────────────────────────────────────────────
async function loadFilters() {
  try {
    const d = await fetch(`${API}/filters`).then(r => r.json())
    lineFilters.value = d.product_lines || []
  } catch (_) {}
}

// ── Products ──────────────────────────────────────────────
async function loadProducts(resetPage = false) {
  if (resetPage) currentPage.value = 0
  loading.value = true
  const params = new URLSearchParams({ limit: PAGE_SIZE, page: currentPage.value + 1 })
  if (filters.search) params.set('search', filters.search)
  if (filters.status) params.set('status', filters.status)
  if (filters.line)   params.set('product_line', filters.line)
  try {
    const d = await fetch(`${API}/list?${params}`).then(r => r.json())
    if (d.status !== 'success') throw new Error()
    products.value = d.products || []
    total.value    = d.total    || 0
  } catch (_) { products.value = [] }
  finally { loading.value = false }
}

const totalPages = computed(() => Math.ceil(total.value / PAGE_SIZE))

// ── Actions ───────────────────────────────────────────────
async function generateDesc(code, inModal = false) {
  rowLoading[code + '_desc'] = true
  try {
    const d = await fetch(`${API}/generate`, {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ magento_ref_code: code })
    }).then(r => r.json())
    if (d.status === 'error') throw new Error(d.message)
    showToast('✅ Đã sinh mô tả thành công')
    updaterow(code, 0)
    loadOverview()
    if (inModal) await openDetail(code, detailName.value)
  } catch (e) { showToast('❌ ' + e.message) }
  finally { rowLoading[code + '_desc'] = false }
}

async function generateTags(code) {
  rowLoading[code + '_tags'] = true
  try {
    const d = await fetch('/api/bulk/generate-tags-single', {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ magento_ref_code: code })
    }).then(r => r.json())
    if (d.status === 'error') throw new Error(d.message)
    showToast('✅ Đã sinh tags')
    const p = products.value.find(x => x.magento_ref_code === code || x.internal_ref_code === code)
    if (p && d.tags) p.tags = d.tags
  } catch (e) { showToast('❌ ' + e.message) }
  finally { rowLoading[code + '_tags'] = false }
}

async function approveRow(code, status) {
  rowLoading[code + '_approve'] = true
  try {
    await fetch(`${API}/approve`, {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ internal_ref_code: code, status })
    })
    updaterow(code, status)
    if (detailData.value) detailData.value.status = status
    loadOverview()
    showToast(status === 1 ? '✅ Đã duyệt' : '↩ Hủy duyệt')
  } catch (e) { showToast('❌ ' + e.message) }
  finally { rowLoading[code + '_approve'] = false }
}

function updaterow(code, status) {
  const p = products.value.find(x => x.magento_ref_code === code || x.internal_ref_code === code)
  if (p) p.desc_status = status
}

// ── Detail modal ──────────────────────────────────────────
async function openDetail(code, name = '') {
  detailOpen.value = true
  detailCode.value = code
  detailName.value = name
  detailData.value = null
  detailTab.value  = 'clean'
  try {
    const d = await fetch(`${API}/saved/${encodeURIComponent(code)}`).then(r => r.json())
    if (d.status === 'success' && d.description) detailData.value = d.description
  } catch (_) {}
}

// ── Batch ─────────────────────────────────────────────────
async function batchGenPage() {
  const codes = products.value.filter(p => p.desc_status === -1).map(getCode)
  if (!codes.length) { showToast('⚠️ Không có SP nào cần sinh'); return }
  if (!confirm(`Sinh AI cho ${codes.length} SP chưa có mô tả?`)) return
  try {
    const d = await fetch(`${API}/batch-generate`, {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ internal_ref_codes: codes })
    }).then(r => r.json())
    showToast(d.message || '✅ Đã đưa vào hàng đợi')
    startPoll()
  } catch (e) { showToast('❌ ' + e.message) }
}

async function batchApprovePage() {
  const codes = products.value.filter(p => p.desc_status === 0).map(getCode)
  if (!codes.length) { showToast('⚠️ Không có SP chờ duyệt'); return }
  if (!confirm(`Duyệt ${codes.length} SP?`)) return
  await Promise.all(codes.map(code => fetch(`${API}/approve`, {
    method: 'POST', headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ internal_ref_code: code, status: 1 })
  })))
  showToast(`✅ Đã duyệt ${codes.length} SP`)
  loadProducts(); loadOverview()
}

const getCode = p => typeof p === 'string' ? p : p.magento_ref_code || p.internal_ref_code

function startPoll() {
  clearInterval(pollTimer)
  pollTimer = setInterval(() => { loadOverview(); loadProducts() }, 5000)
  setTimeout(() => clearInterval(pollTimer), 120000)
}

// ── Toast ─────────────────────────────────────────────────
function showToast(msg) {
  toast.value = msg
  clearTimeout(toastTimer)
  toastTimer = setTimeout(() => toast.value = '', 3000)
}

// ── Badge helpers ─────────────────────────────────────────
function statusVariant(s) {
  if (s === 1)  return 'default'     // approved → primary
  if (s === 0)  return 'secondary'   // pending → muted
  return 'outline'                   // missing → outline
}
function statusLabel(s) {
  if (s === 1)  return 'Đã duyệt'
  if (s === 0)  return 'Chờ duyệt'
  return 'Chưa có'
}

const progressPct = computed(() => {
  if (!overview.value?.has_desc || !overview.value?.approved) return 0
  return Number(((overview.value.approved / overview.value.has_desc) * 100).toFixed(1))
})

onMounted(() => Promise.all([loadOverview(), loadFilters(), loadProducts()]))
onUnmounted(() => clearInterval(pollTimer))
</script>

<template>
  <DashboardLayout>
    <div class="p-6 space-y-6 max-w-[1440px]">

      <!-- Toast -->
      <Transition name="fade">
        <div v-if="toast"
             class="fixed bottom-6 right-6 z-50 rounded-lg border border-border bg-popover px-4 py-2.5 text-sm shadow-lg text-popover-foreground">
          {{ toast }}
        </div>
      </Transition>

      <!-- Header -->
      <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
        <div>
          <h1 class="text-2xl font-bold tracking-tight text-foreground">Product Descriptions</h1>
          <p class="text-sm text-muted-foreground mt-1">Quản lý mô tả AI · sinh tags · duyệt hàng loạt</p>
        </div>
        <div class="flex items-center gap-2">
          <Button variant="outline" size="sm" class="gap-1.5 h-9" @click="batchGenPage">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
            Gen Desc
          </Button>
          <Button size="sm" class="gap-1.5 h-9" @click="batchApprovePage">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
            Duyệt tất cả
          </Button>
        </div>
      </div>

      <!-- Stats Row -->
      <div class="grid grid-cols-2 sm:grid-cols-4 xl:grid-cols-8 gap-3">
        <template v-if="loadingOverview">
          <Card v-for="i in 8" :key="i" class="border-border">
            <CardContent class="p-4"><Skeleton class="h-7 w-full mb-2" /><Skeleton class="h-3 w-3/4" /></CardContent>
          </Card>
        </template>
        <template v-else-if="overview">
          <Card v-for="s in [
            { label:'Tổng SP',     value: overview.total_sr,           color: 'text-foreground' },
            { label:'Đã có DB',    value: overview.has_desc,           color: 'text-primary' },
            { label:'Đã duyệt',   value: overview.approved,           color: 'text-emerald-600' },
            { label:'Chờ duyệt',  value: overview.pending,            color: 'text-amber-500' },
            { label:'Thiếu mô tả',value: Math.max(0,(overview.total_sr||0)-(overview.has_desc||0)), color: 'text-destructive' },
            { label:'Thiếu clean',value: overview.missing_clean_desc, color: 'text-orange-500' },
            { label:'Thiếu tags', value: overview.missing_tags,       color: 'text-rose-500' },
            { label:'Size guide', value: overview.has_size_guide,     color: 'text-blue-500' },
          ]" :key="s.label" class="border-border hover:shadow-sm transition-shadow">
            <CardContent class="p-4 text-center">
              <p :class="['text-xl font-black tabular-nums leading-none', s.color]">{{ (s.value||0).toLocaleString() }}</p>
              <p class="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mt-2 leading-tight">{{ s.label }}</p>
            </CardContent>
          </Card>
        </template>
      </div>

      <!-- Progress bar -->
      <div v-if="overview" class="flex items-center gap-4 bg-muted/30 rounded-xl px-4 py-3 border border-border">
        <div class="flex-1 space-y-1">
          <div class="flex justify-between text-xs font-semibold">
            <span class="text-muted-foreground">Tỷ lệ duyệt</span>
            <span class="text-foreground">{{ progressPct }}%</span>
          </div>
          <Progress :model-value="progressPct" class="h-2" />
        </div>
        <div class="text-sm font-bold text-emerald-600 shrink-0">{{ overview.approved?.toLocaleString() }} / {{ overview.has_desc?.toLocaleString() }}</div>
      </div>

      <!-- Filters -->
      <div class="flex flex-wrap gap-2 items-center bg-muted/20 rounded-xl border border-border px-4 py-3">
        <Input v-model="filters.search" placeholder="Tìm tên, mã SP..." class="w-52 h-9"
               @keydown.enter="loadProducts(true)" />

        <Select v-model="filters.status" @update:modelValue="loadProducts(true)">
          <SelectTrigger class="w-[140px] h-9"><SelectValue placeholder="Trạng thái" /></SelectTrigger>
          <SelectContent>
            <SelectItem value="">Tất cả</SelectItem>
            <SelectItem value="approved">Đã duyệt</SelectItem>
            <SelectItem value="pending">Chờ duyệt</SelectItem>
            <SelectItem value="missing">Chưa có</SelectItem>
          </SelectContent>
        </Select>

        <Select v-model="filters.line" @update:modelValue="loadProducts(true)">
          <SelectTrigger class="w-[180px] h-9"><SelectValue placeholder="Dòng sản phẩm" /></SelectTrigger>
          <SelectContent>
            <SelectItem value="">Tất cả dòng</SelectItem>
            <SelectItem v-for="l in lineFilters" :key="l.product_line_vn" :value="l.product_line_vn">
              {{ l.product_line_vn }} ({{ l.cnt }})
            </SelectItem>
          </SelectContent>
        </Select>

        <Button variant="ghost" size="sm" class="h-9 text-muted-foreground"
                @click="filters.search=''; filters.status=''; filters.line=''; loadProducts(true)">
          Reset
        </Button>
        <span class="ml-auto text-sm font-semibold text-foreground">{{ total.toLocaleString() }} <span class="text-muted-foreground font-normal">sản phẩm</span></span>
      </div>

      <!-- Table -->
      <Card>
        <CardContent class="p-0">
          <!-- Skeleton -->
          <div v-if="loading" class="p-4 space-y-3">
            <Skeleton v-for="i in 8" :key="i" class="h-14 w-full rounded-lg" />
          </div>

          <!-- Empty -->
          <div v-else-if="!products.length"
               class="flex flex-col items-center justify-center py-16 text-muted-foreground gap-2">
            <span class="text-4xl">📭</span>
            <p class="text-sm font-medium">Không tìm thấy sản phẩm</p>
          </div>

          <Table v-else>
            <TableHeader>
              <TableRow>
                <TableHead class="w-[260px]">Sản phẩm</TableHead>
                <TableHead>Dòng SP</TableHead>
                <TableHead class="min-w-[180px]">Tags</TableHead>
                <TableHead>Giá</TableHead>
                <TableHead>Trạng thái</TableHead>
                <TableHead class="text-center w-12">Size</TableHead>
                <TableHead>Cập nhật</TableHead>
                <TableHead class="w-20">Duyệt</TableHead>
                <TableHead class="w-36">Generate</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              <TableRow v-for="p in products" :key="p.magento_ref_code || p.internal_ref_code"
                        class="group cursor-pointer"
                        @click="openDetail(p.magento_ref_code || p.internal_ref_code, p.product_name)">
                <!-- Product -->
                <TableCell>
                  <div class="flex items-center gap-3">
                    <img v-if="p.product_image_url_thumbnail" :src="p.product_image_url_thumbnail"
                         class="w-10 h-10 object-cover rounded-lg shrink-0 bg-muted"
                         loading="lazy" @error="$event.target.style.display='none'" />
                    <div v-else class="w-10 h-10 rounded-lg bg-muted flex items-center justify-center shrink-0">📦</div>
                    <div class="min-w-0">
                      <p class="text-sm font-medium truncate max-w-[160px] group-hover:text-primary transition-colors">
                        {{ p.product_name || '—' }}
                      </p>
                      <p class="text-xs text-muted-foreground font-mono">{{ p.magento_ref_code || p.internal_ref_code }}</p>
                    </div>
                  </div>
                </TableCell>

                <!-- Line -->
                <TableCell class="text-sm text-muted-foreground">{{ p.product_line_vn || '—' }}</TableCell>

                <!-- Tags -->
                <TableCell>
                  <div v-if="p.tags?.length" class="flex flex-wrap gap-1">
                    <Badge v-for="t in p.tags.slice(0,3)" :key="t" variant="outline" class="text-[10px] px-1.5 h-5">
                      {{ t }}
                    </Badge>
                    <span v-if="p.tags.length > 3" class="text-[10px] text-muted-foreground self-center">
                      +{{ p.tags.length - 3 }}
                    </span>
                  </div>
                  <span v-else class="text-muted-foreground text-xs">Chưa có</span>
                </TableCell>

                <!-- Price -->
                <TableCell class="text-sm font-medium tabular-nums">
                  {{ p.sale_price ? Number(p.sale_price).toLocaleString('vi-VN') + '₫' : '—' }}
                </TableCell>

                <!-- Status -->
                <TableCell>
                  <Badge :variant="statusVariant(p.desc_status)" class="text-xs">
                    {{ statusLabel(p.desc_status) }}
                  </Badge>
                </TableCell>

                <!-- Size guide -->
                <TableCell class="text-center">
                  <span v-if="p.has_size_guide" class="text-primary text-sm">✓</span>
                  <span v-else class="text-muted-foreground">—</span>
                </TableCell>

                <!-- Updated -->
                <TableCell class="text-xs text-muted-foreground tabular-nums">
                  {{ p.updated_at ? new Date(p.updated_at).toLocaleDateString('vi-VN') : '—' }}
                </TableCell>

                <!-- Approve -->
                <TableCell @click.stop>
                  <Button v-if="p.desc_status === 0" size="sm" class="h-7 text-xs"
                          :disabled="rowLoading[getCode(p)+'_approve']"
                          @click="approveRow(getCode(p), 1)">
                    Duyệt
                  </Button>
                  <Button v-else-if="p.desc_status === 1" variant="outline" size="sm" class="h-7 text-xs"
                          :disabled="rowLoading[getCode(p)+'_approve']"
                          @click="approveRow(getCode(p), 0)">
                    Hủy
                  </Button>
                  <span v-else class="text-muted-foreground text-xs">—</span>
                </TableCell>

                <!-- Generate -->
                <TableCell @click.stop>
                  <div class="flex flex-col gap-1">
                    <Button variant="outline" size="sm" class="h-6 text-xs px-2"
                            :disabled="rowLoading[getCode(p)+'_desc']"
                            @click="generateDesc(getCode(p))">
                      {{ rowLoading[getCode(p)+'_desc'] ? '⏳' : '✍️ Desc' }}
                    </Button>
                    <Button variant="outline" size="sm" class="h-6 text-xs px-2"
                            :disabled="rowLoading[getCode(p)+'_tags']"
                            @click="generateTags(getCode(p))">
                      {{ rowLoading[getCode(p)+'_tags'] ? '⏳' : '🏷️ Tags' }}
                    </Button>
                  </div>
                </TableCell>
              </TableRow>
            </TableBody>
          </Table>

          <!-- Pagination -->
          <div v-if="totalPages > 1" class="flex items-center justify-between px-4 py-3 border-t border-border">
            <p class="text-xs text-muted-foreground">
              Trang {{ currentPage + 1 }} / {{ totalPages }}
            </p>
            <div class="flex gap-2">
              <Button variant="outline" size="sm"
                      :disabled="currentPage <= 0"
                      @click="currentPage--; loadProducts()">← Trước</Button>
              <Button variant="outline" size="sm"
                      :disabled="currentPage >= totalPages - 1"
                      @click="currentPage++; loadProducts()">Sau →</Button>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>

    <!-- ── Detail Dialog ── -->
    <Dialog v-model:open="detailOpen">
      <DialogContent class="max-w-2xl max-h-[85vh] flex flex-col overflow-hidden">
        <DialogHeader>
          <DialogTitle class="flex items-center gap-2 text-base">
            <span>{{ detailName || detailCode }}</span>
            <Badge variant="outline" class="font-mono text-xs">{{ detailCode }}</Badge>
          </DialogTitle>
        </DialogHeader>

        <div v-if="!detailData" class="flex items-center justify-center py-12 text-muted-foreground gap-2">
          <div class="w-4 h-4 border-2 border-primary border-t-transparent rounded-full animate-spin"></div>
          <span class="text-sm">Đang tải...</span>
        </div>

        <div v-else class="flex-1 flex flex-col overflow-hidden gap-3">
          <!-- Product header -->
          <div class="flex items-center gap-3 p-3 rounded-lg bg-muted/50">
            <img v-if="detailData.product_image_url" :src="detailData.product_image_url"
                 class="w-14 h-14 object-cover rounded-lg" @error="$event.target.style.display='none'" />
            <div class="flex-1 min-w-0">
              <p class="font-semibold text-sm truncate">{{ detailData.product_name || detailCode }}</p>
              <p class="text-xs text-muted-foreground">{{ detailData.product_line }} · {{ detailData.master_color }}</p>
              <Badge :variant="statusVariant(detailData.status)" class="mt-1 text-xs">
                {{ statusLabel(detailData.status) }}
              </Badge>
            </div>
            <div class="flex gap-2 shrink-0">
              <Button variant="outline" size="sm"
                      :disabled="rowLoading[detailCode + '_desc']"
                      @click="generateDesc(detailCode, true)">
                {{ rowLoading[detailCode + '_desc'] ? '⏳ Đang sinh...' : '↻ Regenerate' }}
              </Button>
              <Button v-if="detailData.status === 0" size="sm"
                      @click="approveRow(detailCode, 1)">✓ Duyệt</Button>
              <Button v-else-if="detailData.status === 1" variant="outline" size="sm"
                      @click="approveRow(detailCode, 0)">✕ Hủy</Button>
            </div>
          </div>

          <!-- Tabs -->
          <Tabs v-model="detailTab" class="flex-1 flex flex-col overflow-hidden">
            <TabsList class="shrink-0">
              <TabsTrigger value="clean">Clean Description</TabsTrigger>
              <TabsTrigger value="data">Raw Data</TabsTrigger>
              <TabsTrigger value="tags">Tags ({{ detailData.tags?.length || 0 }})</TabsTrigger>
            </TabsList>

            <TabsContent value="clean" class="flex-1 overflow-y-auto mt-2">
              <div class="rounded-lg bg-muted/40 p-4 text-sm text-foreground/80 whitespace-pre-wrap leading-relaxed font-mono min-h-[200px]">
                {{ detailData.clean_description || detailData.rendered_text || '(Chưa có clean description)' }}
              </div>
            </TabsContent>

            <TabsContent value="data" class="flex-1 overflow-y-auto mt-2">
              <div class="space-y-0 divide-y divide-border rounded-lg border border-border overflow-hidden">
                <div v-for="(val, key) in (detailData.description_data || {})" :key="key"
                     class="flex gap-4 px-4 py-2.5 text-sm hover:bg-muted/30 transition-colors">
                  <span class="text-muted-foreground min-w-[140px] shrink-0 font-medium text-xs pt-0.5">{{ key }}</span>
                  <span class="text-foreground/80 break-words">{{ Array.isArray(val) ? val.join(', ') : val }}</span>
                </div>
                <div v-if="!Object.keys(detailData.description_data || {}).length"
                     class="px-4 py-8 text-sm text-center text-muted-foreground">
                  Không có dữ liệu
                </div>
              </div>
            </TabsContent>

            <TabsContent value="tags" class="flex-1 overflow-y-auto mt-2">
              <div class="flex flex-wrap gap-2 mb-4">
                <Badge v-for="tag in (detailData.tags || [])" :key="tag" variant="secondary" class="text-xs">
                  {{ tag }}
                </Badge>
                <p v-if="!detailData.tags?.length" class="text-sm text-muted-foreground">Chưa có tags</p>
              </div>
              <Button variant="outline" size="sm" @click="generateTags(detailCode)">🏷️ Sinh Tags</Button>
            </TabsContent>
          </Tabs>
        </div>
      </DialogContent>
    </Dialog>

  </DashboardLayout>
</template>

<style scoped>
.fade-enter-active, .fade-leave-active { transition: opacity 0.25s ease }
.fade-enter-from, .fade-leave-to { opacity: 0 }
</style>
