<script setup>
import { ref, onMounted } from 'vue'
import DashboardLayout from '../layouts/DashboardLayout.vue'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } 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 { ScrollArea } from '@/components/ui/scroll-area'

const identityKey = ref('')
const dateFrom = ref(new Date().toISOString().split('T')[0])
const dateTo = ref(new Date().toISOString().split('T')[0])
const messages = ref([])
const loading = ref(false)
const statsBar = ref(null)
const nextCursor = ref(null)
const totalMessages = ref(0)
const totalProducts = ref(0)

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

function formatPrice(p) {
  return p ? Number(p).toLocaleString('vi-VN') + '₫' : ''
}

async function loadHistory(reset = true) {
  const key = identityKey.value.trim()
  if (!key) return alert('Nhập identity key trước!')
  if (reset) { messages.value = []; nextCursor.value = null; totalMessages.value = 0; totalProducts.value = 0 }
  loading.value = true

  const params = new URLSearchParams({ limit: '30' })
  if (nextCursor.value) params.append('before_id', nextCursor.value)
  if (dateFrom.value) params.append('date_from', dateFrom.value)
  if (dateTo.value) params.append('date_to', dateTo.value)

  try {
    const res = await fetch(`/api/check-history/${encodeURIComponent(key)}?${params}`)
    if (!res.ok) throw new Error(`HTTP ${res.status}`)
    const payload = await res.json()
    const items = payload.data || []
    const reversed = reset ? [...items].reverse() : items

    reversed.forEach(item => {
      messages.value.push(item)
      totalMessages.value++
      totalProducts.value += (!item.is_human && item.product_ids?.length) || 0
    })

    nextCursor.value = payload.next_cursor || null
    statsBar.value = { messages: totalMessages.value, products: totalProducts.value, range: dateFrom.value + ' → ' + dateTo.value }
  } catch (e) {
    alert('Lỗi: ' + e.message)
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <DashboardLayout>
    <div class="p-6 md:p-8 max-w-[1200px] mx-auto space-y-6">

      <!-- Header -->
      <div class="flex flex-col gap-1">
        <h1 class="text-2xl font-semibold tracking-tight text-foreground">Chat History</h1>
        <p class="text-sm text-muted-foreground">Tra cứu và phân tích lịch sử trò chuyện theo Identity Key</p>
      </div>

      <Separator />

      <div class="grid grid-cols-1 lg:grid-cols-4 gap-6 items-start">
        <!-- Sidebar Controls -->
        <div class="lg:col-span-1 space-y-4">
          <Card>
            <CardHeader class="pb-3 border-b border-border/50">
              <CardTitle class="text-base">Bộ lọc tìm kiếm</CardTitle>
            </CardHeader>
            <CardContent class="pt-4 space-y-4">
              <div class="space-y-1.5">
                <label class="text-xs font-medium text-foreground">Identity Key</label>
                <Input v-model="identityKey" placeholder="device_id hoặc user_id"
                       class="h-9" @keydown.enter="loadHistory(true)" />
              </div>
              
              <div class="grid grid-cols-2 gap-2">
                <div class="space-y-1.5">
                  <label class="text-xs font-medium text-foreground">Từ ngày</label>
                  <Input type="date" v-model="dateFrom" class="h-9 text-xs" />
                </div>
                <div class="space-y-1.5">
                  <label class="text-xs font-medium text-foreground">Đến ngày</label>
                  <Input type="date" v-model="dateTo" class="h-9 text-xs" />
                </div>
              </div>

              <Button @click="loadHistory(true)" :disabled="loading || !identityKey.trim()" class="w-full h-9">
                {{ loading ? 'Đang tìm...' : 'Tìm kiếm' }}
              </Button>
            </CardContent>
          </Card>

          <Card v-if="statsBar">
            <CardHeader class="pb-2">
              <CardTitle class="text-sm">Thống kê phiên</CardTitle>
            </CardHeader>
            <CardContent class="space-y-3">
              <div class="flex justify-between items-center text-sm">
                <span class="text-muted-foreground">Tin nhắn</span>
                <span class="font-medium text-foreground">{{ statsBar.messages }}</span>
              </div>
              <Separator />
              <div class="flex justify-between items-center text-sm">
                <span class="text-muted-foreground">Sản phẩm BOT</span>
                <span class="font-medium text-foreground">{{ statsBar.products }}</span>
              </div>
              <Separator />
              <div class="flex flex-col gap-1 text-xs text-muted-foreground pt-1">
                <span>Giai đoạn:</span>
                <span class="font-mono text-foreground">{{ statsBar.range }}</span>
              </div>
            </CardContent>
          </Card>
        </div>

        <!-- Chat Area -->
        <Card class="lg:col-span-3 flex flex-col h-[75vh] overflow-hidden bg-muted/20">
          <CardHeader class="p-4 border-b border-border bg-card">
            <div class="flex items-center justify-between">
              <CardTitle class="text-base flex items-center gap-2">
                <span class="w-2 h-2 rounded-full bg-primary animate-pulse" v-if="messages.length"></span>
                Khung trò chuyện
              </CardTitle>
              <Badge variant="outline" class="font-mono text-xs" v-if="identityKey && messages.length">
                {{ identityKey }}
              </Badge>
            </div>
          </CardHeader>

          <CardContent class="flex-1 p-0 overflow-hidden relative">
            <div v-if="!messages.length && !loading" class="absolute inset-0 flex flex-col items-center justify-center text-muted-foreground bg-card/50">
              <svg xmlns="http://www.w3.org/polygons" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" class="mb-4 opacity-20"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg>
              <p class="text-sm font-medium text-foreground">Chưa có dữ liệu</p>
              <p class="text-xs mt-1">Nhập Identity Key để tra cứu lịch sử</p>
            </div>

            <ScrollArea class="h-full px-4 py-6" v-if="messages.length">
              <div class="space-y-6">
                <!-- Load More Top -->
                <div class="flex justify-center" v-if="nextCursor">
                  <Button variant="secondary" size="sm" @click="loadHistory(false)" :disabled="loading" class="rounded-full h-8 text-xs px-4">
                    {{ loading ? 'Đang tải...' : 'Tải thêm tin cũ' }}
                  </Button>
                </div>

                <!-- Chat Bubbles -->
                <div v-for="(msg, i) in messages" :key="i"
                     :class="['flex w-full', msg.is_human ? 'justify-end' : 'justify-start']">
                  <div :class="['max-w-[85%] md:max-w-[75%] rounded-2xl p-4 flex flex-col gap-2 shadow-sm transition-all',
                    msg.is_human ? 'bg-primary text-primary-foreground rounded-tr-sm' : 'bg-card text-card-foreground border border-border rounded-tl-sm']">
                    
                    <div class="flex items-center justify-between gap-4">
                      <span class="text-[11px] font-semibold tracking-wide uppercase opacity-70">
                        {{ msg.is_human ? 'User' : 'Assistant' }}
                      </span>
                      <span class="text-[10px] opacity-60 tabular-nums">
                        {{ formatTime(msg.timestamp) }}
                      </span>
                    </div>

                    <p class="text-sm leading-relaxed whitespace-pre-wrap break-words">{{ msg.message }}</p>

                    <!-- Product Carousel / Cards -->
                    <div v-if="!msg.is_human && msg.product_ids?.length" class="flex flex-wrap gap-2 mt-3 pt-3 border-t border-border/50">
                      <a v-for="p in msg.product_ids" :key="p.sku || p"
                         :href="typeof p === 'object' && p.url ? 'https://canifa.com/' + p.url : '#'"
                         target="_blank"
                         class="group flex items-center gap-3 bg-muted/40 hover:bg-muted border border-transparent hover:border-primary/30 rounded-xl p-2 pr-4 transition-all no-underline w-full sm:w-[calc(50%-0.25rem)] xl:w-[calc(33.333%-0.34rem)]">
                        
                        <div class="w-12 h-12 shrink-0 rounded-md bg-background overflow-hidden border border-border/50">
                          <img v-if="p.thumbnail_image_url" :src="p.thumbnail_image_url" class="w-full h-full object-cover transition-transform group-hover:scale-110" loading="lazy" />
                          <div v-else class="w-full h-full flex items-center justify-center text-muted-foreground text-xs">IMG</div>
                        </div>

                        <div class="min-w-0 flex-1">
                          <p class="font-medium text-xs text-foreground truncate">{{ p.name || p }}</p>
                          <div class="flex items-baseline gap-1 mt-0.5">
                            <p v-if="p.sale_price" class="text-sm font-bold text-primary">{{ formatPrice(p.sale_price) }}</p>
                            <p v-if="p.price && p.price > p.sale_price" class="text-[10px] text-muted-foreground line-through">{{ formatPrice(p.price) }}</p>
                          </div>
                        </div>
                      </a>
                    </div>

                  </div>
                </div>
              </div>
            </ScrollArea>
          </CardContent>
        </Card>
      </div>

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