<script setup>
import { ref, nextTick } from 'vue'
import DashboardLayout from '../layouts/DashboardLayout.vue'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'

// ── State ──
const images = ref([])        // [{ b64, name }]
const messages = ref([{ role: 'ai', text: '👋 Upload hoặc paste hình ảnh, rồi hỏi tao ngay!' }])
const chatInput = ref('')
const sending = ref(false)
const pipeline = ref([])
const pathBadge = ref('')
const messagesEnd = ref(null)
const dropArea = ref(null)

// ── Image Handling ──
function handleFiles(files) {
  Array.from(files).forEach(file => {
    if (!file.type.startsWith('image/')) return
    const reader = new FileReader()
    reader.onload = (e) => {
      images.value.push({ b64: e.target.result, name: file.name })
    }
    reader.readAsDataURL(file)
  })
}

function onDrop(e) {
  e.preventDefault()
  handleFiles(e.dataTransfer.files)
  dropArea.value?.classList.remove('ring-2', 'ring-pink-400')
}
function onDragOver(e) { e.preventDefault(); dropArea.value?.classList.add('ring-2', 'ring-pink-400') }
function onDragLeave()  { dropArea.value?.classList.remove('ring-2', 'ring-pink-400') }

function onPaste(e) {
  if (!e.clipboardData?.items) return
  const files = []
  for (let i = 0; i < e.clipboardData.items.length; i++) {
    if (e.clipboardData.items[i].type.startsWith('image/')) {
      files.push(e.clipboardData.items[i].getAsFile())
    }
  }
  if (files.length) handleFiles(files)
}

function removeImage(idx) { images.value.splice(idx, 1) }

// ── Chat ──
async function sendMsg() {
  const query = chatInput.value.trim()
  const imgs  = [...images.value]
  if (!query && !imgs.length) return
  chatInput.value = ''
  images.value = []
  sending.value = true

  messages.value.push({ role: 'user', text: query || '*(Gửi hình ảnh)*', images: imgs.map(i => i.b64) })
  messages.value.push({ role: 'typing' })
  await nextTick(); messagesEnd.value?.scrollIntoView({ behavior: 'smooth' })

  try {
    const r = await fetch('/api/image-search/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ query, images: imgs.map(i => i.b64) })
    })
    const d = await r.json()
    messages.value = messages.value.filter(m => m.role !== 'typing')

    if (d.status === 'success') {
      messages.value.push({ role: 'ai', text: d.response, meta: `⏱ ${d.elapsed_ms}ms · ${d.agent_path}` })
      pipeline.value = d.pipeline || []
      pathBadge.value = `${d.agent_path} · ${d.elapsed_ms}ms`
    } else {
      messages.value.push({ role: 'error', text: d.message || 'Lỗi xử lý' })
    }
  } catch (e) {
    messages.value = messages.value.filter(m => m.role !== 'typing')
    messages.value.push({ role: 'error', text: 'Lỗi kết nối: ' + e.message })
  } finally {
    sending.value = false
    await nextTick(); messagesEnd.value?.scrollIntoView({ behavior: 'smooth' })
  }
}

function stepClass(step) {
  const map = { tool_call: 'bg-purple-100 text-purple-700', tool_result: 'bg-green-100 text-green-700', thinking: 'bg-amber-100 text-amber-700' }
  return map[step] || 'bg-gray-100 text-gray-600'
}
</script>

<template>
  <DashboardLayout>
    <div class="flex h-[calc(100vh-56px)] overflow-hidden" @paste="onPaste">

      <!-- Chat panel -->
      <div class="w-[420px] shrink-0 flex flex-col border-r border-gray-100">
        <div class="px-4 py-3 border-b bg-gray-50">
          <h2 class="text-sm font-bold text-gray-800">🖼️ Image Search</h2>
          <p class="text-[10px] text-gray-400 mt-0.5">Upload hình → AI tìm sản phẩm tương tự</p>
        </div>

        <!-- Messages -->
        <div class="flex-1 overflow-y-auto p-3 space-y-2.5">
          <div v-for="(msg, i) in messages" :key="i" :class="['flex', msg.role === 'user' ? 'justify-end' : 'justify-start']">
            <div v-if="msg.role === 'user'" class="max-w-[88%] space-y-1">
              <div v-if="msg.images?.length" class="flex flex-wrap gap-1 justify-end">
                <img v-for="(b, ii) in msg.images" :key="ii" :src="b"
                     class="h-20 w-20 object-cover rounded-xl border border-gray-200" />
              </div>
              <div v-if="msg.text && msg.text !== '*(Gửi hình ảnh)*'"
                   class="bg-pink-600 text-white rounded-2xl px-3 py-2 text-xs text-right">{{ msg.text }}</div>
            </div>
            <div v-else-if="msg.role === 'ai'"
                 class="max-w-[88%] bg-white border border-gray-100 rounded-2xl px-3 py-2.5 text-xs text-gray-700 leading-relaxed shadow-sm">
              <p class="whitespace-pre-wrap">{{ msg.text }}</p>
              <p v-if="msg.meta" class="text-[9px] text-gray-400 mt-1">{{ msg.meta }}</p>
            </div>
            <div v-else-if="msg.role === 'error'" class="text-xs text-red-600 bg-red-50 border border-red-100 rounded-xl px-3 py-2">❌ {{ msg.text }}</div>
            <div v-else-if="msg.role === 'typing'" class="flex gap-1 px-3 py-2 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>
          </div>
          <div ref="messagesEnd"></div>
        </div>

        <!-- Drop area + image previews -->
        <div class="px-3 pt-2 pb-1">
          <div v-if="images.length" class="flex flex-wrap gap-1 mb-2">
            <div v-for="(img, i) in images" :key="i" class="relative group">
              <img :src="img.b64" class="w-14 h-14 object-cover rounded-lg border border-gray-200" />
              <button @click="removeImage(i)"
                      class="absolute -top-1 -right-1 bg-red-500 text-white w-4 h-4 rounded-full text-[9px] flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">✕</button>
            </div>
          </div>
          <div ref="dropArea"
               class="border-2 border-dashed border-gray-200 rounded-xl p-3 text-center text-xs text-gray-400 cursor-pointer transition-all hover:border-pink-300 hover:bg-pink-50/30"
               @drop="onDrop" @dragover="onDragOver" @dragleave="onDragLeave"
               @click="$refs.fileInput.click()">
            📸 Kéo ảnh vào đây hoặc Paste (Ctrl+V)
            <input ref="fileInput" type="file" accept="image/*" multiple class="hidden"
                   @change="handleFiles($event.target.files)" />
          </div>
        </div>

        <!-- Input -->
        <div class="p-3 border-t bg-gray-50">
          <div class="flex gap-2">
            <Textarea v-model="chatInput" placeholder="Hỏi về hình ảnh: tìm áo tương tự, mô tả phong cách..."
                      class="flex-1 min-h-[48px] text-xs resize-none"
                      @keydown.enter.prevent.exact="sendMsg" />
            <Button @click="sendMsg" :disabled="sending || (!chatInput.trim() && !images.length)"
                    class="self-end bg-pink-600 hover:bg-pink-700 h-9">
              {{ sending ? '⏳' : '▶' }}
            </Button>
          </div>
        </div>
      </div>

      <!-- Right: Pipeline -->
      <div class="flex-1 overflow-hidden flex flex-col">
        <div class="px-4 py-2 border-b bg-gray-50 flex items-center gap-2">
          <h2 class="text-sm font-bold text-gray-700 flex-1">🔬 Agent Pipeline</h2>
          <span v-if="pathBadge" class="text-[10px] text-gray-400 bg-gray-100 px-2 py-0.5 rounded">{{ pathBadge }}</span>
        </div>
        <div class="flex-1 overflow-y-auto p-4">
          <div v-if="!pipeline.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">Agent steps sẽ hiện ở đây sau khi gửi ảnh</p>
          </div>
          <div v-else class="space-y-2">
            <div v-for="(step, i) in pipeline" :key="i"
                 v-if="step.step !== 'user'"
                 class="rounded-xl border border-gray-100 overflow-hidden">
              <div :class="['text-[10px] font-bold px-3 py-1.5', stepClass(step.step)]">
                {{ step.label }}
              </div>
              <div class="px-3 py-2 text-[10px] text-gray-600 leading-relaxed font-mono whitespace-pre-wrap max-h-40 overflow-y-auto bg-white">
                {{ (step.content || '').slice(0, 500) }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </DashboardLayout>
</template>
