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

const chatInput = ref('')
const sending = ref(false)
const messages = ref([])
const pipeline = ref([])
const pathBadge = ref('')
const messagesEnd = ref(null)

const quickPrompts = [
  'Áo sơ mi trắng nam size L',
  'Váy đầm hoa cho mùa hè',
  'Quần jeans nữ dáng slim',
  'Áo khoác mùa đông unisex',
]

function md(text) {
  if (!text) return ''
  return text
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2" target="_blank" class="text-amber-600 underline">$1</a>')
    .replace(/`(.*?)`/g, '<code class="bg-gray-100 px-1 rounded text-xs font-mono">$1</code>')
    .replace(/\n/g, '<br>')
}

async function sendMsg() {
  const query = chatInput.value.trim()
  if (!query || sending.value) return
  chatInput.value = ''
  sending.value = true
  messages.value.push({ type: 'user', text: query })
  messages.value.push({ type: 'thinking' })

  try {
    const token = localStorage.getItem('canifa_token')
    const resp = await fetch('/api/sku-search/chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...(token ? { 'Authorization': 'Bearer ' + token } : {})
      },
      body: JSON.stringify({ query })
    })
    const data = await resp.json()
    messages.value = messages.value.filter(m => m.type !== 'thinking')

    if (data.status === 'success') {
      messages.value.push({
        type: 'ai', html: md(data.response),
        meta: `⏱ ${data.elapsed_ms}ms · ${data.agent_path}`
      })
      if (data.pipeline?.length) {
        pipeline.value = data.pipeline
        pathBadge.value = `${data.agent_path} · ${data.elapsed_ms}ms`
      }
    } else {
      messages.value.push({ type: 'error', text: '❌ ' + (data.message || 'Lỗi') })
    }
  } catch (e) {
    messages.value = messages.value.filter(m => m.type !== 'thinking')
    messages.value.push({ type: 'error', text: '❌ Lỗi kết nối: ' + e.message })
  } finally {
    sending.value = false
    await nextTick()
    messagesEnd.value?.scrollIntoView({ behavior: 'smooth' })
  }
}

function sendQuick(text) { chatInput.value = text; sendMsg() }
</script>

<template>
  <DashboardLayout>
    <div class="p-6 max-w-6xl">
      <div class="grid grid-cols-[1fr_340px] gap-5 h-[calc(100vh-100px)]">

        <!-- Chat left -->
        <div class="flex flex-col">
          <div class="mb-4">
            <h1 class="text-2xl font-black text-gray-900">🔍 SKU Search Chat</h1>
            <p class="text-xs text-gray-500 mt-0.5">Chat để tìm kiếm sản phẩm theo SKU, tên, đặc điểm</p>
          </div>

          <!-- Quick prompts -->
          <div class="flex gap-2 flex-wrap mb-3">
            <button v-for="q in quickPrompts" :key="q"
                    @click="sendQuick(q)"
                    class="px-3 py-1.5 bg-gray-50 hover:bg-amber-50 hover:border-amber-300 border border-gray-100 rounded-full text-xs text-gray-600 transition-colors">
              {{ q }}
            </button>
          </div>

          <!-- Messages -->
          <div class="flex-1 border border-gray-100 rounded-2xl bg-gray-50/50 overflow-y-auto p-4 space-y-3">
            <div v-if="!messages.length" class="flex flex-col items-center justify-center h-full text-gray-400">
              <div class="text-4xl mb-2">🔍</div>
              <p class="text-sm">Nhập câu hỏi hoặc chọn prompt bên trên</p>
            </div>

            <div v-for="(msg, i) in messages" :key="i"
                 :class="['flex', msg.type === 'user' ? 'justify-end' : 'justify-start']">

              <!-- Thinking -->
              <div v-if="msg.type === 'thinking'" class="flex gap-1 px-4 py-3 bg-white border border-gray-100 rounded-2xl shadow-sm">
                <span v-for="j in 3" :key="j" class="w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce"
                      :style="{ animationDelay: j * 150 + 'ms' }"></span>
              </div>

              <!-- User message -->
              <div v-else-if="msg.type === 'user'"
                   class="max-w-[75%] bg-amber-600 text-white px-4 py-2.5 rounded-2xl text-sm">
                {{ msg.text }}
              </div>

              <!-- AI message -->
              <div v-else-if="msg.type === 'ai'"
                   class="max-w-[80%] bg-white border border-gray-100 rounded-2xl px-4 py-3 shadow-sm">
                <div class="text-sm leading-relaxed prose-sm" v-html="msg.html"></div>
                <p v-if="msg.meta" class="text-[10px] text-gray-400 mt-2 border-t border-gray-100 pt-1.5">{{ msg.meta }}</p>
              </div>

              <!-- Error -->
              <div v-else-if="msg.type === 'error'"
                   class="max-w-[80%] bg-red-50 border border-red-100 text-red-700 px-4 py-2.5 rounded-2xl text-sm">
                {{ msg.text }}
              </div>
            </div>
            <div ref="messagesEnd"></div>
          </div>

          <!-- Composer -->
          <div class="flex gap-2 mt-3">
            <Input v-model="chatInput" placeholder="Tìm sản phẩm... (VD: áo sơ mi trắng nam size L)"
                   @keydown.enter="sendMsg" class="flex-1" />
            <Button @click="sendMsg" :disabled="sending || !chatInput.trim()">
              {{ sending ? '⏳' : 'Gửi' }}
            </Button>
          </div>
        </div>

        <!-- Pipeline right -->
        <div class="flex flex-col">
          <div class="flex items-center justify-between mb-3">
            <h2 class="text-sm font-bold text-gray-700">🔧 Agent Pipeline</h2>
            <Badge v-if="pathBadge" variant="outline" class="text-[10px]">{{ pathBadge }}</Badge>
          </div>

          <Card class="flex-1 overflow-hidden">
            <CardContent class="p-0 h-full">
              <ScrollArea class="h-full p-3">
                <div v-if="!pipeline.length" class="text-center py-8 text-gray-400 text-xs">
                  Pipeline sẽ hiện sau khi gửi tin nhắn
                </div>
                <div class="space-y-2">
                  <div v-for="(step, i) in pipeline" :key="i"
                       :class="['border rounded-lg p-2.5 text-xs',
                         step.step === 'user' ? 'border-gray-200 bg-gray-50' :
                         step.step === 'planner' ? 'border-blue-200 bg-blue-50/50' :
                         step.step === 'tool_result' ? 'border-green-200 bg-green-50/50' :
                         'border-amber-200 bg-amber-50/50']">
                    <p class="font-bold text-gray-600 mb-1">{{ step.label }}</p>

                    <p v-if="step.content && step.step !== 'planner'" class="text-gray-600 line-clamp-3">
                      {{ step.content }}
                    </p>

                    <!-- Tool calls -->
                    <div v-if="step.tool_calls?.length">
                      <div v-for="tc in step.tool_calls" :key="tc.name" class="mt-1.5 space-y-0.5">
                        <div class="flex gap-1.5">
                          <span class="text-blue-600">🔧 tool:</span>
                          <span class="font-mono font-semibold">{{ tc.name }}</span>
                        </div>
                        <div v-for="(v, k) in (tc.args || {})" :key="k"
                             v-if="v !== null && v !== undefined && v !== ''"
                             class="flex gap-1.5 pl-4">
                          <span class="text-gray-400">{{ k }}:</span>
                          <span class="font-mono">{{ v }}</span>
                        </div>
                      </div>
                    </div>

                    <!-- Raw JSON expand -->
                    <details v-if="step.raw_json" class="mt-1.5">
                      <summary class="cursor-pointer text-blue-500 hover:text-blue-700">📋 Raw JSON</summary>
                      <pre class="bg-gray-900 text-green-300 rounded p-2 mt-1 text-[10px] overflow-auto max-h-32">{{ step.raw_json }}</pre>
                    </details>
                  </div>
                </div>
              </ScrollArea>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  </DashboardLayout>
</template>
