<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import DashboardLayout from '../layouts/DashboardLayout.vue'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { Card, CardContent } from '@/components/ui/card'

const sessionId = ref('diagram_' + Date.now().toString(36))
const chatInput = ref('')
const messages = ref([{ role: 'system', text: '💬 Diagram Agent sẵn sàng. Mô tả flow/system bạn muốn vẽ!' }])
const sending = ref(false)
const diagramSvg = ref('')
const mermaidCode = ref('')
const diagramTitle = ref('Chưa có diagram')
const diagramType = ref('')
const elapsed = ref('')
const zoom = ref(1)
const panX = ref(0), panY = ref(0)
const isDragging = ref(false)
const dragStart = ref({ x: 0, y: 0, px: 0, py: 0 })
const showCode = ref(false)
const canvasRef = ref(null)
const messagesEnd = ref(null)

const QUICK_PROMPTS = [
  'Vẽ flow chatbot RAG pipeline',
  'Kiến trúc microservices Canifa',
  'User journey từ landing → checkout',
  'Lead funnel từ chatbot → sale',
]

async function sendMessage() {
  const query = chatInput.value.trim()
  if (!query || sending.value) return
  chatInput.value = ''; sending.value = true
  messages.value.push({ role: 'user', text: query })
  messages.value.push({ role: 'typing' })

  try {
    const r = await fetch('/api/diagram/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ query, session_id: sessionId.value })
    })
    const d = await r.json()
    messages.value = messages.value.filter(m => m.role !== 'typing')

    if (d.status === 'success') {
      if (d.diagram?.mermaid_code) {
        await renderMermaid(d.diagram.mermaid_code, d.diagram.title, d.diagram.diagram_type)
      }
      if (d.response) messages.value.push({ role: 'ai', text: d.response })
      elapsed.value = `⏱ ${d.elapsed_ms}ms · ${d.agent_path || ''}`
    } 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 }
}

async function renderMermaid(code, title = '', type = '') {
  mermaidCode.value = code
  diagramTitle.value = title ? `📊 ${title}` : '📊 Diagram'
  diagramType.value = type

  try {
    if (!window.mermaid) {
      diagramSvg.value = `<pre class="text-xs p-4">${code}</pre>`
      return
    }
    const id = 'mermaid_' + Date.now()
    const { svg } = await window.mermaid.render(id, code)
    diagramSvg.value = svg
    zoom.value = 1; panX.value = 40; panY.value = 40
  } catch (e) {
    diagramSvg.value = `<div class="p-4 text-red-600 text-xs">⚠️ Render error: ${e.message}<pre class="mt-2 text-gray-500">${code}</pre></div>`
  }
}

function wheel(e) {
  e.preventDefault()
  const delta = e.deltaY > 0 ? -0.1 : 0.1
  zoom.value = Math.min(Math.max(zoom.value + delta, 0.1), 5)
}

function mouseDown(e) {
  if (e.button !== 0) return
  isDragging.value = true
  dragStart.value = { x: e.clientX, y: e.clientY, px: panX.value, py: panY.value }
  canvasRef.value?.classList.add('cursor-grabbing')
}

function mouseMove(e) {
  if (!isDragging.value) return
  panX.value = dragStart.value.px + (e.clientX - dragStart.value.x)
  panY.value = dragStart.value.py + (e.clientY - dragStart.value.y)
}

function mouseUp() { isDragging.value = false; canvasRef.value?.classList.remove('cursor-grabbing') }

function fitView() { zoom.value = 0.8; panX.value = 40; panY.value = 40 }

function exportPNG() {
  const svg = canvasRef.value?.querySelector('svg')
  if (!svg) return
  const svgData = new XMLSerializer().serializeToString(svg)
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  const img = new Image()
  img.onload = () => {
    canvas.width = img.width * 2; canvas.height = img.height * 2
    ctx.scale(2, 2); ctx.fillStyle = '#f9f8f6'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.drawImage(img, 0, 0)
    const a = document.createElement('a'); a.download = 'diagram.png'; a.href = canvas.toDataURL(); a.click()
  }
  img.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgData)))
}

async function clearChat() {
  messages.value = [{ role: 'system', text: '💬 Chat đã xoá. Bắt đầu lại nào!' }]
  diagramSvg.value = ''; diagramTitle.value = 'Chưa có diagram'; mermaidCode.value = ''; elapsed.value = ''
  try { await fetch('/api/diagram/clear', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ session_id: sessionId.value }) }) } catch (_) {}
}

onMounted(() => {
  window.addEventListener('mousemove', mouseMove)
  window.addEventListener('mouseup', mouseUp)
  // Load Mermaid
  if (!window.mermaid) {
    const s = document.createElement('script')
    s.src = 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js'
    s.onload = () => { window.mermaid.initialize({ startOnLoad: false, theme: 'default' }) }
    document.head.appendChild(s)
  }
})
onUnmounted(() => { window.removeEventListener('mousemove', mouseMove); window.removeEventListener('mouseup', mouseUp) })
</script>

<template>
  <DashboardLayout>
    <div class="flex h-[calc(100vh-56px)] overflow-hidden">
      <!-- Chat panel -->
      <div class="w-[340px] shrink-0 flex flex-col border-r border-gray-100">
        <div class="flex items-center gap-2 px-4 py-3 border-b bg-gray-50">
          <h2 class="text-sm font-bold text-gray-700 flex-1">📊 Diagram Agent</h2>
          <button @click="clearChat" class="text-xs text-gray-400 hover:text-gray-700">🗑</button>
        </div>
        <div class="flex-1 overflow-y-auto p-3 space-y-2">
          <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-[85%] bg-blue-600 text-white rounded-2xl px-3 py-2 text-xs">{{ msg.text }}</div>
            <div v-else-if="msg.role === 'ai'" class="max-w-[85%] bg-white border border-gray-100 rounded-2xl px-3 py-2.5 text-xs text-gray-700 leading-relaxed shadow-sm">{{ msg.text }}</div>
            <div v-else-if="msg.role === 'system'" class="text-xs text-gray-400 italic text-center w-full">{{ msg.text }}</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">
              <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>
        <!-- Quick prompts -->
        <div class="px-3 pb-2 flex flex-wrap gap-1">
          <button v-for="q in QUICK_PROMPTS" :key="q"
                  @click="chatInput = q; sendMessage()"
                  class="text-[10px] bg-blue-50 text-blue-700 px-2 py-0.5 rounded-full hover:bg-blue-100 transition-colors">
            {{ q }}
          </button>
        </div>
        <div class="p-3 border-t bg-gray-50">
          <div class="flex gap-2">
            <Textarea v-model="chatInput" placeholder="Mô tả flow hoặc system bạn muốn vẽ..."
                      class="flex-1 min-h-[56px] text-xs resize-none"
                      @keydown.enter.prevent.exact="sendMessage" />
            <Button @click="sendMessage" :disabled="sending || !chatInput.trim()" class="self-end bg-blue-600 hover:bg-blue-700 h-9">
              {{ sending ? '⏳' : '▶' }}
            </Button>
          </div>
        </div>
      </div>

      <!-- Diagram panel -->
      <div class="flex-1 overflow-hidden flex flex-col">
        <div class="flex items-center gap-2 px-4 py-2 border-b bg-gray-50">
          <h2 class="text-sm font-bold text-gray-700 flex-1 truncate">{{ diagramTitle }}</h2>
          <span class="text-[10px] text-gray-400">{{ diagramType }}</span>
          <span class="text-[10px] text-gray-400">{{ elapsed }}</span>
          <div class="flex gap-1 ml-2">
            <button @click="zoom = Math.max(zoom - 0.15, 0.1)" class="text-xs w-6 h-6 border border-gray-200 rounded hover:bg-gray-100">-</button>
            <button @click="fitView" class="text-[10px] px-1.5 border border-gray-200 rounded hover:bg-gray-100">{{ Math.round(zoom * 100) }}%</button>
            <button @click="zoom = Math.min(zoom + 0.15, 5)" class="text-xs w-6 h-6 border border-gray-200 rounded hover:bg-gray-100">+</button>
            <button @click="showCode = !showCode" class="text-[10px] px-2 border border-gray-200 rounded hover:bg-gray-100">{ }</button>
            <button @click="exportPNG" class="text-[10px] px-2 border border-gray-200 rounded hover:bg-gray-100">📥</button>
          </div>
        </div>

        <!-- Code viewer -->
        <div v-if="showCode && mermaidCode" class="border-b bg-gray-900 text-green-400 px-4 py-2 max-h-40 overflow-y-auto">
          <pre class="text-[10px] font-mono">{{ mermaidCode }}</pre>
        </div>

        <!-- Diagram canvas -->
        <div class="flex-1 overflow-hidden bg-[#f8f7f5] relative cursor-grab"
             ref="canvasRef"
             @wheel="wheel"
             @mousedown="mouseDown">
          <div v-if="!diagramSvg" class="flex flex-col items-center justify-center h-full text-gray-400">
            <div class="text-5xl mb-3">📊</div>
            <p class="text-sm">Mô tả flow hoặc system để AI vẽ diagram</p>
          </div>
          <div v-else
               :style="{ transform: `translate(${panX}px, ${panY}px) scale(${zoom})`, transformOrigin: '0 0', transition: isDragging ? 'none' : 'transform 0.1s' }"
               v-html="diagramSvg">
          </div>
        </div>
      </div>
    </div>
  </DashboardLayout>
</template>
