<script setup>
import { ref, onMounted } from 'vue'
import DashboardLayout from '../layouts/DashboardLayout.vue'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Separator } from '@/components/ui/separator'

const OCC_LABELS = {
  hang_ngay: '🌤️ Hàng ngày',
  di_lam:    '💼 Đi làm',
  di_choi:   '🛍️ Đi chơi',
  di_tiec:   '🎉 Đi tiệc',
  the_thao:  '⚡ Thể thao',
  mac_nha:   '🏠 Mặc nhà',
}
const ROLE_LABELS = {
  bottom:    { label: 'Quần / Chân váy', emoji: '👖' },
  outerwear: { label: 'Layer ngoài',     emoji: '🧥' },
  accessory: { label: 'Phụ kiện',        emoji: '👜' },
}

const products = ref([])
const total = ref(0)
const currentPage = ref(1)
const totalPages = ref(1)
const searchQ = ref('')
const loading = ref(false)

const selectedCode = ref(null)
const selectedProduct = ref(null)
const aiMatches = ref({})
const activeOcc = ref('hang_ngay')
const loadingDetail = ref(false)
const generating = ref(false)
const toastMsg = ref('')

let searchTimer = null

async function loadList(page = 1) {
  loading.value = true
  currentPage.value = page
  try {
    let url = `/api/product-desc/list?page=${page}&limit=20`
    if (searchQ.value) url += `&search=${encodeURIComponent(searchQ.value)}`
    const r = await fetch(url)
    const d = await r.json()
    products.value  = d.items || []
    total.value     = d.total || 0
    totalPages.value = Math.max(1, Math.ceil(total.value / 20))
  } catch (_) { products.value = [] }
  finally { loading.value = false }
}

function onSearch() {
  clearTimeout(searchTimer)
  searchTimer = setTimeout(() => loadList(1), 300)
}

async function loadProduct(code) {
  selectedCode.value  = code
  loadingDetail.value = true
  aiMatches.value     = {}
  // activeOcc should be dynamically set when data loads correctly
  try {
    const [metaRes, fmRes] = await Promise.all([
      fetch(`/api/product-desc/saved/${encodeURIComponent(code)}`),
      fetch(`/api/fashion-matches/${encodeURIComponent(code)}`),
    ])
    const meta = await metaRes.json()
    const fm   = await fmRes.json()
    const desc = meta.description || {}
    selectedProduct.value = {
      name:  (desc.description_data || desc.description || {}).ten_san_pham || desc.product_name || code,
      code,
      image: desc.product_image_url || '',
      line:  desc.product_line || '',
      color: desc.master_color  || '',
    }
    aiMatches.value = fm.ok ? (fm.ai_matches || {}) : {}
    if (!aiMatches.value[activeOcc.value] && Object.keys(aiMatches.value).length > 0) {
      activeOcc.value = Object.keys(aiMatches.value)[0] || 'hang_ngay'
    }
  } catch (e) { showToast('❌ Lỗi tải: ' + e.message) }
  finally { loadingDetail.value = false }
}

async function generateMatches() {
  if (!selectedCode.value || generating.value) return
  generating.value = true
  try {
    const r = await fetch(`/api/fashion-matches/${encodeURIComponent(selectedCode.value)}/generate`, { method: 'POST' })
    const d = await r.json()
    if (d.ok) {
      aiMatches.value = d.ai_matches || {}
      showToast('✅ Đã tạo phối đồ!')
      loadList(currentPage.value)
    } else { showToast('❌ ' + (d.error || 'Lỗi generate')) }
  } catch (e) { showToast('❌ ' + e.message) }
  finally { generating.value = false }
}

async function removeMatch(occ, role, idx) {
  const updated = { ...aiMatches.value }
  updated[occ] = { ...(updated[occ] || {}) }
  updated[occ][role] = [...(updated[occ][role] || [])]
  updated[occ][role].splice(idx, 1)
  aiMatches.value = updated
  try {
    await fetch(`/api/fashion-matches/${encodeURIComponent(selectedCode.value)}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ ai_matches: updated })
    })
    showToast('✅ Đã xoá')
  } catch (_) {}
}

function showToast(msg) {
  toastMsg.value = msg
  setTimeout(() => toastMsg.value = '', 3000)
}

function occCount(occ) {
  const d = aiMatches.value[occ] || {}
  return Object.values(d).reduce((s, a) => s + (Array.isArray(a) ? a.length : 0), 0)
}

onMounted(() => loadList(1))
</script>

<template>
  <DashboardLayout>
    <div class="h-[calc(100vh-theme(spacing.16))] flex overflow-hidden bg-background">
      
      <!-- Toast using standard popover colors -->
      <Transition name="fade">
        <div v-if="toastMsg" class="fixed bottom-6 right-6 z-50 bg-popover text-popover-foreground border border-border px-4 py-2 rounded-lg shadow-lg text-sm font-medium">
          {{ toastMsg }}
        </div>
      </Transition>

      <!-- Left: Product List sidebar -->
      <div class="w-[320px] shrink-0 flex flex-col border-r border-border bg-card">
        <div class="p-4 space-y-3 border-b border-border">
          <div>
            <h2 class="font-semibold text-foreground tracking-tight">Fashion Matches</h2>
            <p class="text-xs text-muted-foreground mt-0.5">Xây dựng &amp; duyệt phối đồ AI</p>
          </div>
          <div class="space-y-1">
            <Input v-model="searchQ" placeholder="🔍 Tìm tên, mã SP..." @input="onSearch" class="h-9 text-xs" />
            <p class="text-[10px] text-muted-foreground text-right" v-if="total">{{ total }} sản phẩm</p>
          </div>
        </div>

        <ScrollArea class="flex-1">
          <div v-if="loading" class="flex flex-col items-center justify-center py-12 gap-2 text-muted-foreground">
            <div class="w-4 h-4 border-2 border-primary border-t-transparent rounded-full animate-spin"></div>
            <span class="text-xs">Đang tải danh sách...</span>
          </div>
          <div v-else-if="!products.length" class="flex items-center justify-center py-12 text-xs text-muted-foreground">
            Không tìm thấy sản phẩm
          </div>
          <div v-else class="p-2 space-y-1">
            <div v-for="p in products" :key="p.code"
                 @click="loadProduct(p.code)"
                 :class="['flex items-center gap-3 px-3 py-3 cursor-pointer rounded-lg transition-colors',
                           selectedCode === p.code ? 'bg-primary/10 text-primary hover:bg-primary/15' : 'hover:bg-accent hover:text-accent-foreground']">
              
              <div class="w-10 h-10 rounded-md overflow-hidden bg-muted border border-border/50 shrink-0">
                <img v-if="p.image_url" :src="p.image_url" class="w-full h-full object-cover" @error="$event.target.style.display='none'" />
              </div>
              
              <div class="flex-1 min-w-0">
                <p class="text-sm font-medium truncate" :class="selectedCode === p.code ? 'text-primary' : 'text-foreground'">{{ p.name || p.code }}</p>
                <div class="flex items-center justify-between mt-1">
                  <span class="text-[10px] text-muted-foreground font-mono">{{ p.code }}</span>
                  <Badge :variant="p.has_ai_matches ? 'default' : 'secondary'" class="text-[9px] h-4 px-1 py-0">
                    {{ p.has_ai_matches ? '✓ Có mix' : 'Chưa có' }}
                  </Badge>
                </div>
              </div>
            </div>
          </div>
        </ScrollArea>

        <!-- Pagination Footer -->
        <div class="flex items-center justify-between p-3 border-t border-border bg-muted/20">
          <Button variant="outline" size="sm" class="h-8 px-2 text-xs" @click="loadList(currentPage - 1)" :disabled="currentPage <= 1">
            ← Trước
          </Button>
          <span class="text-xs text-muted-foreground font-medium">{{ currentPage }} / {{ totalPages }}</span>
          <Button variant="outline" size="sm" class="h-8 px-2 text-xs" @click="loadList(currentPage + 1)" :disabled="currentPage >= totalPages">
            Sau →
          </Button>
        </div>
      </div>

      <!-- Right: Detail Panel -->
      <div class="flex-1 flex flex-col bg-muted/20 relative">
        <div v-if="!selectedCode" class="absolute inset-0 flex flex-col items-center justify-center 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="mb-4 opacity-20"><rect width="18" height="18" x="3" y="3" rx="2"/><path d="M3 9h18"/><path d="M9 21V9"/></svg>
          <p class="text-sm font-medium text-foreground">Chọn một sản phẩm</p>
          <p class="text-xs mt-1">Click vào danh sách bên trái để sinh hoặc duyệt phối đồ AI</p>
        </div>

        <div v-else-if="loadingDetail" class="absolute inset-0 flex flex-col items-center justify-center text-muted-foreground bg-background/50 z-10 backdrop-blur-sm">
          <div class="w-6 h-6 border-2 border-primary border-t-transparent rounded-full animate-spin mb-4"></div>
          <p class="text-xs font-medium">Đang tải dữ liệu sản phẩm...</p>
        </div>

        <template v-else-if="selectedProduct">
          <!-- Detail Header -->
          <div class="flex items-center justify-between p-6 border-b border-border bg-card">
            <div class="flex items-center gap-4">
              <div class="w-16 h-16 rounded-xl overflow-hidden bg-muted border border-border shadow-sm shrink-0">
                <img v-if="selectedProduct.image" :src="selectedProduct.image" class="w-full h-full object-cover" @error="$event.target.style.display='none'" />
              </div>
              <div>
                <h2 class="text-lg font-bold text-foreground">{{ selectedProduct.name }}</h2>
                <p class="text-xs text-muted-foreground font-mono mt-0.5">{{ selectedProduct.code }}</p>
                <div class="flex flex-wrap gap-2 mt-2">
                  <Badge variant="secondary" v-if="selectedProduct.line" class="text-[10px] font-normal">{{ selectedProduct.line }}</Badge>
                  <Badge variant="outline" v-if="selectedProduct.color" class="text-[10px]">{{ selectedProduct.color }}</Badge>
                </div>
              </div>
            </div>
            
            <Button @click="generateMatches" :disabled="generating" class="gap-2 shadow-sm">
              <span v-if="generating" class="w-3 h-3 border-2 border-primary-foreground border-t-transparent rounded-full animate-spin"></span>
              <span v-else>✨</span>
              {{ generating ? 'Đang tạo...' : 'Generate Matches' }}
            </Button>
          </div>

          <!-- Matching logic Tabs -->
          <div class="flex-1 flex flex-col overflow-hidden p-6 gap-4">
            <Tabs v-model="activeOcc" class="flex-1 flex flex-col min-h-0">
              <TabsList class="flex w-max mb-6 h-10 bg-accent/50 p-1">
                <TabsTrigger v-for="(label, occ) in OCC_LABELS" :key="occ" :value="occ" class="text-xs data-[state=active]:bg-background data-[state=active]:shadow-sm px-4">
                  {{ label }}
                  <Badge variant="secondary" class="ml-2 h-4 px-1 py-0 text-[9px]" v-if="occCount(occ)">{{ occCount(occ) }}</Badge>
                </TabsTrigger>
              </TabsList>

              <div class="flex-1 overflow-y-auto pr-2 rounded-lg border border-border bg-card">
                <div v-if="!Object.keys(aiMatches).length" class="flex flex-col items-center justify-center p-12 text-muted-foreground h-full text-center">
                  <div class="w-12 h-12 rounded-full bg-accent flex items-center justify-center mb-3">🎨</div>
                  <p class="text-sm font-medium text-foreground">Sản phẩm này chưa có bản phối đồ nào</p>
                  <p class="text-xs mt-1">Hệ thống AI sẽ gợi ý Quần, Áo khoác, Phụ kiện phù hợp. Nhấn Generate để bắt đầu.</p>
                </div>
                
                <div v-else class="p-6 space-y-8">
                  <div v-for="(roleLabel, role) in ROLE_LABELS" :key="role">
                    <div class="flex items-center gap-2 mb-4">
                      <div class="w-8 h-8 rounded-lg bg-accent flex items-center justify-center text-sm shadow-xs border border-border">{{ roleLabel.emoji }}</div>
                      <h3 class="text-sm font-semibold text-foreground">{{ roleLabel.label }}</h3>
                    </div>
                    
                    <div v-if="!(aiMatches[activeOcc] && aiMatches[activeOcc][role] && aiMatches[activeOcc][role].length)"
                         class="text-xs text-muted-foreground/70 italic px-4 py-3 rounded-md bg-accent/50 border border-border/50">
                      Không có gợi ý {{ roleLabel.label.toLowerCase() }} cho mục đích này.
                    </div>
                    
                    <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                      <div v-for="(item, idx) in aiMatches[activeOcc][role]" :key="idx"
                           class="group relative flex items-start gap-3 bg-background border border-border rounded-xl p-3 shadow-sm hover:shadow-md hover:border-primary/30 transition-all">
                        
                        <div class="w-16 h-16 rounded-md bg-muted border border-border/50 shrink-0 overflow-hidden">
                          <img v-if="item.image_url" :src="item.image_url" class="w-full h-full object-cover" @error="$event.target.style.display='none'" />
                        </div>
                        
                        <div class="flex-1 min-w-0 pr-6">
                          <p class="text-xs font-semibold text-foreground truncate" :title="item.name || item.code">{{ item.name || item.code }}</p>
                          <p class="text-[10px] text-muted-foreground font-mono mt-0.5">{{ item.code }}</p>
                          <p v-if="item.reason" class="text-[10px] text-primary/80 mt-1.5 leading-tight line-clamp-2" :title="item.reason">{{ item.reason }}</p>
                        </div>

                        <button @click="removeMatch(activeOcc, role, idx)" 
                                class="absolute top-2 right-2 opacity-0 group-hover:opacity-100 p-1.5 rounded-md hover:bg-destructive/10 hover:text-destructive text-muted-foreground transition-all">
                          <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>
                  </div>
                </div>
              </div>
            </Tabs>
          </div>
        </template>
      </div>
    </div>
  </DashboardLayout>
</template>

<style scoped>
.fade-enter-active, .fade-leave-active { transition: opacity .2s ease-out }
.fade-enter-from, .fade-leave-to { opacity: 0; transform: translateY(10px) }
</style>
