<script setup>
import { ref, onMounted, nextTick } 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 { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { ScrollArea } from '@/components/ui/scroll-area'

function generateUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    const r = Math.random() * 16 | 0
    return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16)
  })
}

const userId = ref('nick_a')
const deviceId = ref('device-' + generateUUID().substring(0, 8))
const isAuthenticated = ref(false)
const identityKey = ref('')
const messages = ref([])
const chatInput = ref('')
const sending = ref(false)
const status = ref('Ready.')
const jsonOutput = ref({})
const showConversations = ref(false)
const conversations = ref([])
const historyBox = ref(null)
const showDebug = ref(false)

function normalizeContent(raw) {
  let content = raw || '(empty)'
  if (typeof content === 'string' && content.startsWith('{') && content.includes('ai_response')) {
    try { content = JSON.parse(content).ai_response || content } catch (_) {}
  }
  return content
}

async function callApi(url, options = {}) {
  status.value = 'Loading ' + url + '...'
  const res = await fetch(url, options)
  const data = await res.json()
  jsonOutput.value = data
  status.value = `Done ${url} (HTTP ${res.status})`
  return data
}

async function loadHistory() {
  const key = isAuthenticated.value ? userId.value : deviceId.value
  const data = await callApi('/api/mock/history', {
    method: 'POST', headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ identity_key: key, is_authenticated: isAuthenticated.value, limit: 50 })
  })
  identityKey.value = key
  messages.value = (data.history || []).map(item => ({
    role: item.role || (item.is_human ? 'human' : 'ai'),
    text: normalizeContent(item.message || item.content),
    ts: item.timestamp || item.created_at || ''
  }))
  await nextTick()
}

async function loadConversationList() {
  const key = isAuthenticated.value ? userId.value : deviceId.value
  const data = await callApi('/api/mock/conversations', {
    method: 'POST', headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ identity_key: key, is_authenticated: isAuthenticated.value })
  })
  conversations.value = data.conversations || []
}

async function toggleAuth() {
  const uid = userId.value.trim() || 'nick_a'
  const did = deviceId.value.trim()
  if (!isAuthenticated.value) {
    const data = await callApi('/api/mock/login', {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ user_id: uid, device_id: did })
    })
    isAuthenticated.value = true
    identityKey.value = uid
    messages.value = (data.history || []).map(i => ({
      role: i.role || (i.is_human ? 'human' : 'ai'),
      text: normalizeContent(i.message || i.content),
      ts: i.timestamp || ''
    }))
  } else {
    const data = await callApi('/api/mock/logout', {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ device_id: did })
    })
    isAuthenticated.value = false
    identityKey.value = did
    messages.value = (data.history || []).map(i => ({
      role: i.role || (i.is_human ? 'human' : 'ai'),
      text: normalizeContent(i.message || i.content),
      ts: i.timestamp || ''
    }))
  }
}

async function newConversation() {
  const key = isAuthenticated.value ? userId.value : deviceId.value
  await callApi('/api/mock/new-conversation', {
    method: 'POST', headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ identity_key: key })
  })
  await loadHistory()
}

async function sendMessage() {
  const msg = chatInput.value.trim()
  if (!msg || sending.value) return
  sending.value = true
  const key = isAuthenticated.value ? userId.value : deviceId.value
  chatInput.value = ''
  await callApi('/api/mock/chat', {
    method: 'POST', headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ identity_key: key, message: msg, use_real_ai: true, is_authenticated: isAuthenticated.value, device_id: deviceId.value })
  })
  await loadHistory()
  sending.value = false
}

onMounted(() => { identityKey.value = deviceId.value })
</script>

<template>
  <DashboardLayout>
    <div class="h-[calc(100vh-theme(spacing.16))] flex flex-col gap-0 p-6 max-w-[1400px] mx-auto">

      <!-- Header -->
      <div class="mb-4 flex flex-col sm:flex-row items-start sm:items-center gap-3 justify-between shrink-0">
        <div>
          <h1 class="text-2xl font-bold tracking-tight text-foreground">Merge History Chat</h1>
          <p class="text-sm text-muted-foreground mt-0.5">Kiểm tra logic merge lịch sử chat Guest → Registered User</p>
        </div>
        <Badge variant="outline" class="text-xs font-mono px-3 py-1 shrink-0 bg-muted/40">
          Identity: <span class="text-primary ml-1">{{ identityKey || '—' }}</span>
        </Badge>
      </div>

      <div class="flex-1 flex gap-5 min-h-0">
        <!-- ─── Left sidebar ─── -->
        <div class="w-72 shrink-0 flex flex-col gap-4">

          <!-- Identity Config -->
          <Card class="border-border">
            <CardHeader class="pb-3 pt-4 px-4">
              <CardTitle class="text-sm flex items-center gap-2">
                <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="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
                Identity Config
              </CardTitle>
            </CardHeader>
            <CardContent class="px-4 pb-4 space-y-3">
              <div class="space-y-1.5">
                <Label class="text-xs font-medium">User ID</Label>
                <Input v-model="userId" placeholder="user_id" class="h-8 text-sm font-mono" />
              </div>
              <div class="space-y-1.5">
                <Label class="text-xs font-medium">Device ID</Label>
                <Input v-model="deviceId" placeholder="device_id" class="h-8 text-sm font-mono text-muted-foreground" />
              </div>

              <div class="pt-2">
                <Badge :variant="isAuthenticated ? 'default' : 'secondary'" class="text-xs w-full flex justify-center py-1.5">
                  {{ isAuthenticated ? '✅ Đã đăng nhập' : '🌐 Guest Session' }}
                </Badge>
              </div>

              <Button size="sm"
                :variant="isAuthenticated ? 'destructive' : 'default'"
                class="w-full h-8 text-xs"
                @click="toggleAuth">
                {{ isAuthenticated ? 'Đăng xuất' : 'Đăng nhập' }}
              </Button>
            </CardContent>
          </Card>

          <!-- Actions -->
          <Card class="border-border">
            <CardHeader class="pb-2 pt-4 px-4">
              <CardTitle class="text-sm">Thao tác API</CardTitle>
            </CardHeader>
            <CardContent class="px-4 pb-4 grid grid-cols-2 gap-2">
              <Button size="sm" variant="outline" class="h-8 text-xs w-full" @click="loadHistory">
                <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mr-1"><path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/></svg>
                History
              </Button>
              <Button size="sm" variant="outline" class="h-8 text-xs w-full" @click="newConversation">
                + New Conv
              </Button>
              <Button size="sm" variant="outline" class="h-8 text-xs w-full" @click="showConversations = !showConversations; loadConversationList()">
                {{ showConversations ? 'Hide' : 'View' }} Convs
              </Button>
              <Button size="sm" variant="outline" class="h-8 text-xs w-full" @click="callApi('/api/merge-history/mock')">
                Load Mock
              </Button>
              <Button size="sm" variant="outline" class="h-8 text-xs w-full col-span-2"
                @click="callApi('/api/merge-history/preview', { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({ user_id: userId, device_id: deviceId }) })">
                Preview Merge
              </Button>
              <Button size="sm" variant="outline" class="h-8 text-xs w-full col-span-2"
                @click="callApi('/api/merge-history/guest/' + encodeURIComponent(deviceId))">
                Guest Timeline
              </Button>
            </CardContent>
          </Card>

          <!-- Conversations list -->
          <Card v-if="showConversations" class="flex-1 overflow-hidden border-border">
            <CardHeader class="pb-2 pt-3 px-4">
              <CardTitle class="text-xs uppercase tracking-wider text-muted-foreground">Conversations</CardTitle>
            </CardHeader>
            <CardContent class="px-4 pb-3">
              <ScrollArea class="max-h-36">
                <div v-if="!conversations.length" class="text-xs text-muted-foreground py-2">Chưa có hội thoại nào.</div>
                <div v-for="conv in conversations" :key="conv.identity_key"
                     class="border border-border rounded-lg p-2.5 text-xs mb-2 hover:bg-accent/30 transition-colors">
                  <p class="font-semibold text-foreground truncate">{{ conv.identity_key }}</p>
                  <p class="text-muted-foreground mt-0.5">{{ conv.message_count }} msgs · {{ conv.last_message_at || 'n/a' }}</p>
                </div>
              </ScrollArea>
            </CardContent>
          </Card>

          <!-- Status -->
          <div class="px-1">
            <p class="text-[10px] text-muted-foreground/60 font-mono leading-relaxed truncate">{{ status }}</p>
          </div>
        </div>

        <!-- ─── Chat Panel ─── -->
        <Card class="flex-1 flex flex-col min-h-0 overflow-hidden border-border">
          <!-- Chat header -->
          <div class="flex items-center justify-between px-5 py-3 border-b border-border bg-muted/10 shrink-0">
            <div>
              <p class="font-semibold text-sm text-foreground">Chatbot Conversation</p>
              <p class="text-[10px] text-muted-foreground font-mono">/api/mock/chat</p>
            </div>
            <div class="flex items-center gap-2">
              <div class="flex items-center gap-1.5">
                <span :class="['w-2 h-2 rounded-full', isAuthenticated ? 'bg-emerald-500' : 'bg-amber-400']"></span>
                <span class="text-xs font-medium text-foreground">{{ isAuthenticated ? 'Authenticated' : 'Guest' }}</span>
              </div>
            </div>
          </div>

          <!-- Messages -->
          <ScrollArea class="flex-1 px-4 py-4" ref="historyBox">
            <div class="space-y-3 flex flex-col">
              <div v-if="!messages.length" class="flex flex-col items-center justify-center h-full py-20 text-muted-foreground">
                <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="opacity-20 mb-3"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
                <p class="text-sm font-medium text-foreground">Chưa có tin nhắn</p>
                <p class="text-xs mt-1">Nhấn "History" hoặc gửi tin nhắn để bắt đầu.</p>
              </div>
              <div v-for="(msg, i) in messages" :key="i"
                   :class="['flex', msg.role === 'human' ? 'justify-end' : 'justify-start']">
                <div :class="['max-w-[75%] rounded-2xl px-4 py-3 shadow-sm',
                  msg.role === 'human'
                    ? 'bg-primary text-primary-foreground rounded-br-none'
                    : 'bg-muted text-foreground border border-border rounded-bl-none']">
                  <p class="text-[9px] font-bold opacity-50 mb-1 uppercase tracking-wider">{{ msg.role }}</p>
                  <p class="text-sm leading-relaxed">{{ msg.text }}</p>
                  <p class="text-[9px] opacity-40 text-right mt-2 font-mono">{{ msg.ts }}</p>
                </div>
              </div>

              <!-- Sending indicator -->
              <div v-if="sending" class="flex justify-start">
                <div class="bg-muted border border-border rounded-2xl rounded-bl-none px-4 py-3 flex items-center gap-2">
                  <span class="w-1.5 h-1.5 bg-muted-foreground/50 rounded-full animate-bounce [animation-delay:-0.3s]"></span>
                  <span class="w-1.5 h-1.5 bg-muted-foreground/50 rounded-full animate-bounce [animation-delay:-0.15s]"></span>
                  <span class="w-1.5 h-1.5 bg-muted-foreground/50 rounded-full animate-bounce"></span>
                </div>
              </div>
            </div>
          </ScrollArea>

          <!-- Composer -->
          <div class="border-t border-border bg-background p-3 flex gap-2 shrink-0">
            <Input v-model="chatInput"
                   placeholder="Nhập tin nhắn và nhấn Enter..."
                   @keydown.enter="sendMessage"
                   class="flex-1 h-10 shadow-none" />
            <Button @click="sendMessage"
                    :disabled="sending || !chatInput.trim()"
                    class="h-10 px-5">
              <span v-if="sending" class="w-4 h-4 border-2 border-primary-foreground border-t-transparent animate-spin rounded-full"></span>
              <span v-else>Gửi</span>
            </Button>
          </div>
        </Card>
      </div>

      <!-- Debug JSON Toggle -->
      <div class="mt-4 shrink-0">
        <button @click="showDebug = !showDebug"
                class="w-full flex items-center justify-between px-4 py-2.5 rounded-xl border border-border bg-muted/20 hover:bg-muted/50 transition-colors text-xs font-medium text-muted-foreground">
          <span class="flex items-center gap-2">
            <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="M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z"/><path d="M12 8v4"/><path d="M12 16h.01"/></svg>
            Debug JSON Output
          </span>
          <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" :class="['transition-transform', showDebug ? 'rotate-180' : '']"><path d="m6 9 6 6 6-6"/></svg>
        </button>
        <div v-if="showDebug" class="mt-2 rounded-xl overflow-hidden border border-primary/20 shadow-md">
          <div class="bg-[#1e1e1e] px-4 py-2 flex items-center gap-2 border-b border-white/5">
            <span class="w-3 h-3 rounded-full bg-red-500/70"></span>
            <span class="w-3 h-3 rounded-full bg-yellow-500/70"></span>
            <span class="w-3 h-3 rounded-full bg-green-500/70"></span>
          </div>
          <pre class="bg-[#1e1e1e] text-green-400 text-xs p-4 max-h-64 overflow-auto font-mono leading-relaxed">{{ JSON.stringify(jsonOutput, null, 2) }}</pre>
        </div>
      </div>
    </div>
  </DashboardLayout>
</template>
