<script setup>
import { ref, reactive, computed, onMounted } 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 {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow, TableEmpty
} from '@/components/ui/table'
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue
} from '@/components/ui/select'

const LIMIT = 50
const overview    = ref(null)
const productLines = ref([])
const genders_data = ref([])
const products    = ref([])
const total       = ref(0)
const loading     = ref(false)
const loadingOverview = ref(true)
const colorFilters = ref([])
const lineFilters  = ref([])

const filters = reactive({ search: '', gender: '', color: '', line: '', sort: 'quantity_sold', isNew: false, hasDiscount: false })
const offset  = ref(0)

const expandedColors = reactive({})
const colorData      = reactive({})

let searchTimer = null

// ── Helpers ────────────────────────────────────────────────
const fmt  = n => n == null ? '—' : Number(n).toLocaleString('vi-VN')
const fmtK = n => {
  if (!n && n !== 0) return '—'
  if (n >= 1e6) return (n / 1e6).toFixed(1) + 'M'
  if (n >= 1e3) return Math.round(n / 1e3) + 'K'
  return fmt(n)
}
const genderLabel = g =>
  g === 'men' ? 'Nam' : g === 'women' ? 'Nữ' : g === 'unisex' ? 'Unisex' : g === 'kids' ? 'Kids' : g || '—'

const clock = ref('')
function updateClock() { clock.value = new Date().toLocaleTimeString('vi-VN') }

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

// ── API calls ──────────────────────────────────────────────
async function loadOverview() {
  loadingOverview.value = true
  try {
    const d = await fetch('/api/products/overview').then(r => r.json())
    if (d.status !== 'success') return
    overview.value = d.stats
    productLines.value = d.product_lines || []
    genders_data.value  = d.genders || []
  } catch (_) {}
  finally { loadingOverview.value = false }
}

async function loadFilterOptions() {
  try {
    const d = await fetch('/api/products/filters').then(r => r.json())
    colorFilters.value = d.colors || []
    lineFilters.value  = d.product_lines || []
  } catch (_) {}
}

async function loadProducts(resetOffset = false) {
  if (resetOffset) offset.value = 0
  loading.value = true
  try {
    const order = filters.sort === 'product_name' ? 'asc' : 'desc'
    let url = `/api/products/list?sort=${filters.sort}&order=${order}&limit=${LIMIT}&offset=${offset.value}`
    if (filters.gender)      url += `&gender=${filters.gender}`
    if (filters.search)      url += `&search=${encodeURIComponent(filters.search)}`
    if (filters.color)       url += `&color=${encodeURIComponent(filters.color)}`
    if (filters.line)        url += `&product_line=${encodeURIComponent(filters.line)}`
    if (filters.isNew)       url += '&is_new=true'
    if (filters.hasDiscount) url += '&has_discount=true'
    const d = await fetch(url).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 }
}

function onSearch() {
  clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    if (filters.search && filters.sort === 'quantity_sold') filters.sort = 'relevance'
    else if (!filters.search && filters.sort === 'relevance') filters.sort = 'quantity_sold'
    loadProducts(true)
  }, 350)
}

async function toggleColors(code) {
  if (expandedColors[code]) { expandedColors[code] = false; return }
  expandedColors[code] = true
  if (colorData[code]) return
  try {
    const d = await fetch(`/api/products/colors?code=${encodeURIComponent(code)}`).then(r => r.json())
    colorData[code] = d.variants || []
  } catch (_) { colorData[code] = [] }
}

const maxSold = computed(() => Math.max(...products.value.map(p => p.quantity_sold || 0), 1))
const soldPct  = p => Math.min(((p.quantity_sold || 0) / maxSold.value) * 100, 100)

onMounted(() => {
  updateClock(); setInterval(updateClock, 1000)
  Promise.all([loadFilterOptions(), loadOverview(), loadProducts()])
})

const kpis = computed(() => !overview.value ? [] : [
  { label: 'Tổng SP',      value: fmt(overview.value.total_products),  desc: 'real-time' },
  { label: 'Dòng SP',      value: fmt(overview.value.total_lines),     desc: 'loại' },
  { label: 'Giá TB',       value: fmtK(overview.value.avg_price)+'₫',  desc: fmtK(overview.value.min_price)+'₫ — '+fmtK(overview.value.max_price)+'₫' },
  { label: 'Giảm giá',     value: fmt(overview.value.discounted_count), desc: 'SP đang KM' },
  { label: 'Mới',          value: fmt(overview.value.new_count),        desc: 'is_new' },
  { label: 'Đã bán',       value: fmt(overview.value.total_sold),       desc: fmt(overview.value.selling_count)+' SP có đơn' },
])
</script>

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

      <!-- Header -->
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-xl font-semibold tracking-tight">Sản phẩm</h1>
          <p class="text-sm text-muted-foreground">StarRocks real-time · {{ clock }}</p>
        </div>
        <Badge variant="outline" class="text-xs">
          {{ fmt(total) }} sản phẩm
        </Badge>
      </div>

      <Separator />

      <!-- KPI Cards -->
      <div class="grid grid-cols-3 md:grid-cols-6 gap-3">
        <template v-if="loadingOverview">
          <Card v-for="i in 6" :key="i">
            <CardContent class="p-4">
              <Skeleton class="h-6 w-16 mb-2" />
              <Skeleton class="h-3 w-24" />
            </CardContent>
          </Card>
        </template>
        <template v-else>
          <Card v-for="kpi in kpis" :key="kpi.label" class="hover:shadow-sm transition-shadow">
            <CardContent class="p-4">
              <p class="text-lg font-bold text-foreground">{{ kpi.value }}</p>
              <p class="text-xs font-medium text-foreground/80 mt-0.5">{{ kpi.label }}</p>
              <p class="text-[10px] text-muted-foreground mt-1 truncate">{{ kpi.desc }}</p>
            </CardContent>
          </Card>
        </template>
      </div>

      <!-- Breakdown -->
      <div v-if="productLines.length" class="grid grid-cols-2 gap-4">
        <Card>
          <CardHeader class="pb-2 pt-4 px-4">
            <CardTitle class="text-sm">Dòng sản phẩm</CardTitle>
          </CardHeader>
          <CardContent class="px-4 pb-4">
            <div class="space-y-1.5 max-h-36 overflow-y-auto">
              <div v-for="l in productLines.slice(0,12)" :key="l.product_line_vn"
                   class="flex justify-between items-center text-xs py-0.5">
                <span class="text-foreground/80 truncate max-w-[180px]">{{ l.product_line_vn || 'N/A' }}</span>
                <span class="text-muted-foreground font-mono shrink-0">{{ fmt(l.count) }}</span>
              </div>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader class="pb-2 pt-4 px-4">
            <CardTitle class="text-sm">Giới tính</CardTitle>
          </CardHeader>
          <CardContent class="px-4 pb-4">
            <div class="space-y-1.5">
              <div v-for="g in genders_data" :key="g.gender_by_product"
                   class="flex justify-between items-center text-xs py-0.5">
                <span class="text-foreground/80">{{ genderLabel(g.gender_by_product) }}</span>
                <span class="text-muted-foreground font-mono">{{ fmt(g.count) }} SP</span>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      <!-- Filters -->
      <div class="flex flex-wrap gap-2 items-center">
        <Input v-model="filters.search" placeholder="Tìm sản phẩm..." class="w-52 h-9"
               @input="onSearch" />

        <Select v-model="filters.gender" @update:modelValue="loadProducts(true)">
          <SelectTrigger class="w-[120px] h-9"><SelectValue placeholder="Giới tính" /></SelectTrigger>
          <SelectContent>
            <SelectItem value="">Tất cả</SelectItem>
            <SelectItem value="women">Nữ</SelectItem>
            <SelectItem value="men">Nam</SelectItem>
            <SelectItem value="unisex">Unisex</SelectItem>
            <SelectItem value="kids">Trẻ em</SelectItem>
          </SelectContent>
        </Select>

        <Select v-model="filters.color" @update:modelValue="loadProducts(true)">
          <SelectTrigger class="w-[140px] h-9"><SelectValue placeholder="Màu sắc" /></SelectTrigger>
          <SelectContent>
            <SelectItem value="">Tất cả màu</SelectItem>
            <SelectItem v-for="c in colorFilters" :key="c.master_color" :value="c.master_color">
              {{ c.master_color.split('/')[0].trim() }} ({{ c.cnt }})
            </SelectItem>
          </SelectContent>
        </Select>

        <Select v-model="filters.line" @update:modelValue="loadProducts(true)">
          <SelectTrigger class="w-[160px] h-9"><SelectValue placeholder="Dòng SP" /></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>

        <Select v-model="filters.sort" @update:modelValue="loadProducts(true)">
          <SelectTrigger class="w-[130px] h-9"><SelectValue placeholder="Sắp xếp" /></SelectTrigger>
          <SelectContent>
            <SelectItem value="quantity_sold">Bán chạy</SelectItem>
            <SelectItem value="sale_price">Giá bán</SelectItem>
            <SelectItem value="product_name">Tên A-Z</SelectItem>
            <SelectItem value="relevance">Relevance</SelectItem>
          </SelectContent>
        </Select>

        <Button
          :variant="filters.isNew ? 'default' : 'outline'" size="sm"
          class="h-9" @click="filters.isNew = !filters.isNew; loadProducts(true)">
          Mới
        </Button>
        <Button
          :variant="filters.hasDiscount ? 'default' : 'outline'" size="sm"
          class="h-9" @click="filters.hasDiscount = !filters.hasDiscount; loadProducts(true)">
          Giảm giá
        </Button>
      </div>

      <!-- Table -->
      <Card>
        <CardContent class="p-0">
          <!-- Loading 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">
            <div class="text-4xl mb-3">📭</div>
            <p class="text-sm font-medium">Không tìm thấy sản phẩm</p>
            <p class="text-xs mt-1">Thử thay đổi bộ lọc</p>
          </div>

          <!-- Data Table -->
          <Table v-else>
            <TableHeader>
              <TableRow>
                <TableHead class="w-[280px]">Sản phẩm</TableHead>
                <TableHead>Giá bán</TableHead>
                <TableHead>Giảm</TableHead>
                <TableHead class="min-w-[140px]">Đã bán</TableHead>
                <TableHead>Màu</TableHead>
                <TableHead>Dòng SP</TableHead>
                <TableHead>GT</TableHead>
                <TableHead class="w-16">Link</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              <template v-for="p in products" :key="p.internal_ref_code">
                <TableRow class="group">
                  <!-- Product info -->
                  <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 text-lg shrink-0">📦</div>
                      <div class="min-w-0">
                        <div class="flex items-center gap-1.5">
                          <span class="text-sm font-medium truncate max-w-[200px]">{{ p.product_name || '—' }}</span>
                          <Badge v-if="p.is_new_product" variant="secondary" class="text-[9px] px-1 py-0 h-4">NEW</Badge>
                        </div>
                        <p class="text-xs text-muted-foreground font-mono">{{ p.internal_ref_code }}</p>
                        <div v-if="p.size_scale" class="flex flex-wrap gap-0.5 mt-0.5">
                          <span v-for="sz in p.size_scale.split('|').slice(0,5)" :key="sz"
                                class="text-[9px] px-1 border border-border rounded text-muted-foreground">{{ sz.trim() }}</span>
                        </div>
                      </div>
                    </div>
                  </TableCell>

                  <!-- Price -->
                  <TableCell>
                    <p class="text-sm font-semibold">{{ fmtK(p.sale_price) }}₫</p>
                    <p v-if="p.original_price > p.sale_price"
                       class="text-xs text-muted-foreground line-through">{{ fmtK(p.original_price) }}₫</p>
                  </TableCell>

                  <!-- Discount -->
                  <TableCell>
                    <Badge v-if="p.discount_percent > 0" variant="destructive" class="text-xs">
                      -{{ p.discount_percent }}%
                    </Badge>
                    <span v-else class="text-muted-foreground">—</span>
                  </TableCell>

                  <!-- Sold bar -->
                  <TableCell>
                    <div class="flex items-center gap-2">
                      <div class="w-20 h-1.5 bg-muted rounded-full overflow-hidden">
                        <div class="h-full bg-primary rounded-full transition-all"
                             :style="{ width: soldPct(p) + '%', opacity: 0.4 + soldPct(p)/100*0.6 }"></div>
                      </div>
                      <span class="text-sm font-medium tabular-nums">{{ fmt(p.quantity_sold || 0) }}</span>
                    </div>
                  </TableCell>

                  <!-- Colors -->
                  <TableCell>
                    <Button variant="outline" size="sm" class="h-7 text-xs gap-1"
                            @click="toggleColors(p.internal_ref_code)">
                      🎨 {{ p.color_count || 1 }}
                      <span class="text-muted-foreground">{{ expandedColors[p.internal_ref_code] ? '▲' : '▼' }}</span>
                    </Button>
                  </TableCell>

                  <!-- Line -->
                  <TableCell>
                    <Badge variant="secondary" class="text-xs truncate max-w-[120px]">
                      {{ p.product_line_vn || '—' }}
                    </Badge>
                  </TableCell>

                  <!-- Gender -->
                  <TableCell class="text-sm text-muted-foreground">
                    {{ genderLabel(p.gender_by_product) }}
                  </TableCell>

                  <!-- Link -->
                  <TableCell>
                    <a v-if="p.product_web_url" :href="p.product_web_url" target="_blank"
                       class="text-xs text-primary hover:underline">↗ Web</a>
                    <span v-else class="text-muted-foreground">—</span>
                  </TableCell>
                </TableRow>

                <!-- Color expand row -->
                <TableRow v-if="expandedColors[p.internal_ref_code]"
                          :key="p.internal_ref_code+'_colors'" class="bg-muted/30 hover:bg-muted/30">
                  <TableCell colspan="8" class="py-3 px-4">
                    <div v-if="!colorData[p.internal_ref_code]" class="text-xs text-muted-foreground">⏳ Đang tải...</div>
                    <div v-else-if="!colorData[p.internal_ref_code].length" class="text-xs text-muted-foreground">Không có dữ liệu màu</div>
                    <div v-else class="flex flex-wrap gap-2">
                      <div v-for="v in colorData[p.internal_ref_code]" :key="v.product_color_code"
                           class="flex items-center gap-2 bg-card border border-border rounded-lg px-3 py-2 shadow-xs">
                        <img v-if="v.product_image_url_thumbnail" :src="v.product_image_url_thumbnail"
                             class="w-8 h-8 object-cover rounded-md" loading="lazy" />
                        <div v-else class="w-8 h-8 rounded-md bg-muted flex items-center justify-center text-sm">🎨</div>
                        <div>
                          <p class="font-mono text-xs font-semibold">{{ v.product_color_code }}</p>
                          <p class="text-[10px] text-muted-foreground">{{ v.master_color }} · {{ fmt(v.quantity_sold||0) }} bán</p>
                        </div>
                      </div>
                    </div>
                  </TableCell>
                </TableRow>
              </template>
            </TableBody>
          </Table>

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

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