<script setup>
import { ref, onMounted, nextTick } from 'vue'
import DashboardLayout from '../layouts/DashboardLayout.vue'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Badge } from '@/components/ui/badge'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'

const model = ref('gemini-2.0-flash')
const promptInput = ref('')
const sending = ref(false)
const messages = ref([])
const reportHtml = ref('')
const showReport = ref(false)
const convTitle = ref('Hội thoại mới')
const convHistory = ref([])
const showHistory = ref(false)
const currentConvId = ref(null)
const messagesEnd = ref(null)

function uuidv4() {
  return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, c =>
    (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
  )
}

function getToken() { return localStorage.getItem('canifa_token') || '' }

async function authFetch(url, opts = {}) {
  opts.headers = { ...opts.headers, 'Authorization': 'Bearer ' + getToken() }
  return fetch(url, opts)
}

async function loadHistory() {
  try {
    const r = await authFetch('/api/reports/conversations')
    const d = await r.json()
    convHistory.value = d.conversations || []
  } catch (_) {}
}

async function loadConversation(convId) {
  currentConvId.value = convId
  showHistory.value = false
  messages.value = [{ type: 'thinking' }]
  try {
    const r = await authFetch(`/api/reports/conversations/${convId}`)
    const d = await r.json()
    messages.value = d.messages?.map(m => ({
      type: m.is_human ? 'user' : 'ai',
      text: m.text || ''
    })) || []
    if (d.reports?.length) {
      await viewReport(d.reports[d.reports.length - 1].id)
    }
    convTitle.value = 'Hội thoại đã lưu'
  } catch (_) { messages.value = [{ type: 'error', text: 'Lỗi tải dữ liệu' }] }
}

function startNew() {
  currentConvId.value = uuidv4()
  messages.value = [{
    type: 'ai',
    text: '👋 Chào sếp, hệ thống Báo cáo & Phân tích Dữ liệu sẵn sàng.\n\nSếp muốn tạo báo cáo doanh thu, tồn kho hay tra cứu thông tin gì?'
  }]
  reportHtml.value = ''
  showReport.value = false
  convTitle.value = 'Hội thoại mới'
  showHistory.value = false
}

async function viewReport(reportId) {
  reportHtml.value = '<div class="p-8 text-center text-gray-400">⏳ Đang tải báo cáo...</div>'
  showReport.value = true
  try {
    const r = await authFetch(`/api/reports/${reportId}`)
    const d = await r.json()
    if (d.report?.html_content) reportHtml.value = d.report.html_content
  } catch (_) {}
}

async function submit() {
  const question = promptInput.value.trim()
  if (!question || sending.value) return
  promptInput.value = ''
  sending.value = true

  messages.value.push({ type: 'user', text: question })
  const agentMsg = { type: 'ai', text: '', thinking: true, steps: [] }
  messages.value.push(agentMsg)
  await nextTick(); messagesEnd.value?.scrollIntoView({ behavior: 'smooth' })

  try {
    const r = await authFetch('/api/report-html', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ question, conversation_id: currentConvId.value, model: model.value })
    })

    const ct = r.headers.get('content-type') || ''
    if (ct.includes('application/json')) {
      const d = await r.json()
      if (d.mode === 'queued' && d.task_id) {
        connectTaskStream(d.task_id, agentMsg)
      }
    } else {
      // Direct SSE
      const reader = r.body.getReader()
      const decoder = new TextDecoder()
      let buf = ''
      while (true) {
        const { value, done } = await reader.read()
        if (done) break
        buf += decoder.decode(value, { stream: true })
        const lines = buf.split('\n')
        buf = lines.pop()
        for (const line of lines) {
          if (line.startsWith('data: ')) {
            try { handleEvent(JSON.parse(line.slice(6)), agentMsg) } catch (_) {}
          }
        }
      }
    }
  } catch (e) {
    agentMsg.text = '❌ Lỗi kết nối: ' + e.message
    agentMsg.thinking = false
  } finally { sending.value = false }
}

function connectTaskStream(taskId, agentMsg) {
  const src = new EventSource(`/api/report-html/stream/${taskId}?last_id=0-0`)
  src.onmessage = (e) => {
    try {
      const data = JSON.parse(e.data)
      handleEvent(data, agentMsg)
      if (data.type === 'done' || data.type === 'error') src.close()
    } catch (_) {}
  }
  src.onerror = () => src.close()
}

function handleEvent(data, msg) {
  switch (data.type) {
    case 'thinking':
      msg.steps.push({ icon: '⚙️', label: data.step || '...' })
      break
    case 'plan_ready':
      msg.steps.push({ icon: '📋', label: `${data.current_task} — ${data.tools_count} queries` })
      break
    case 'tool_call':
      msg.steps.push({ icon: '🔧', label: (data.tool || '') + ': ' + (data.purpose || '') })
      break
    case 'tool_result':
      msg.steps.push({ icon: data.success ? '✅' : '❌', label: `${data.tool} — ${data.preview?.row_count || 0} rows` })
      break
    case 'reflect':
      msg.steps.push({ icon: data.data_sufficient ? '✅' : '🔄', label: data.data_sufficient ? 'Đủ dữ liệu → đang viết...' : `Cần thêm data (vòng ${data.cycle})` })
      break
    case 'html_token':
      if (!reportHtml.value) showReport.value = true
      reportHtml.value = (reportHtml.value || '') + data.token
      break
    case 'html_complete':
      reportHtml.value = data.html || reportHtml.value
      msg.thinking = false
      msg.text = `✅ Báo cáo đã tạo xong!`
      loadHistory()
      break
    case 'direct_response':
      msg.thinking = false
      msg.text = data.message
      break
    case 'done':
      msg.thinking = false
      break
    case 'error':
      msg.thinking = false
      msg.text = '❌ ' + (data.message || 'Lỗi')
      break
  }
}

onMounted(() => {
  startNew()
  loadHistory()
})
</script>

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

      <!-- History sidebar overlay -->
      <div v-if="showHistory" class="fixed inset-0 z-40 flex">
        <div class="w-72 bg-white border-r border-gray-100 shadow-xl flex flex-col">
          <div class="flex items-center justify-between p-4 border-b">
            <h3 class="font-bold text-sm text-gray-800">📜 Lịch sử báo cáo</h3>
            <Button variant="ghost" size="sm" @click="showHistory = false">✕</Button>
          </div>
          <div class="p-2 flex-1 overflow-y-auto">
            <button @click="startNew" class="w-full text-left px-3 py-2 text-xs text-amber-700 bg-amber-50 rounded-lg mb-2 hover:bg-amber-100">
              + Hội thoại mới
            </button>
            <div v-for="c in convHistory" :key="c.conversation_id"
                 @click="loadConversation(c.conversation_id)"
                 class="px-3 py-2 rounded-lg hover:bg-gray-50 cursor-pointer mb-1">
              <p class="text-xs font-medium text-gray-700 truncate">{{ c.title || 'Hội thoại' }}</p>
              <p class="text-[10px] text-gray-400">{{ new Date(c.updated_at).toLocaleString('vi-VN') }}</p>
            </div>
            <div v-if="!convHistory.length" class="text-center py-8 text-xs text-gray-400">Chưa có lịch sử</div>
          </div>
        </div>
        <div class="flex-1 bg-black/20" @click="showHistory = false"></div>
      </div>

      <!-- Chat panel -->
      <div class="w-[380px] shrink-0 flex flex-col border-r border-gray-100 bg-white">
        <!-- Header -->
        <div class="flex items-center gap-2 px-4 py-3 border-b bg-gray-50">
          <button @click="showHistory = true" class="text-gray-500 hover:text-gray-800 transition-colors">
            <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"/></svg>
          </button>
          <h2 class="text-sm font-bold text-gray-700 flex-1 truncate">{{ convTitle }}</h2>
          <Select v-model="model" class="w-36">
            <SelectTrigger class="h-7 text-[10px]"><SelectValue /></SelectTrigger>
            <SelectContent>
              <SelectItem value="gemini-2.0-flash">Gemini 2.0 Flash</SelectItem>
              <SelectItem value="gemini-2.5-pro">Gemini 2.5 Pro</SelectItem>
              <SelectItem value="gpt-4o">GPT-4o</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <!-- Messages -->
        <div class="flex-1 overflow-y-auto p-3 space-y-3">
          <div v-for="(msg, i) in messages" :key="i"
               :class="['flex', msg.type === 'user' ? 'justify-end' : 'justify-start']">

            <!-- User -->
            <div v-if="msg.type === 'user'"
                 class="max-w-[85%] bg-amber-600 text-white rounded-2xl px-3 py-2.5 text-xs leading-relaxed">
              {{ msg.text }}
            </div>

            <!-- AI -->
            <div v-else-if="msg.type === 'ai'"
                 class="max-w-[85%] bg-white border border-gray-100 rounded-2xl px-3 py-2.5 shadow-sm">
              <!-- Thinking steps -->
              <div v-if="msg.steps?.length" class="space-y-1 mb-2">
                <div v-for="(step, si) in msg.steps" :key="si"
                     class="flex items-center gap-1.5 text-[10px] text-gray-500">
                  <span>{{ step.icon }}</span>
                  <span class="truncate">{{ step.label }}</span>
                </div>
              </div>
              <!-- Typing animation -->
              <div v-if="msg.thinking && !msg.steps?.length" class="flex gap-1 py-1">
                <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>
              <!-- Text -->
              <p v-if="msg.text" class="text-xs leading-relaxed text-gray-700 whitespace-pre-wrap">{{ msg.text }}</p>
            </div>

            <!-- Error -->
            <div v-else-if="msg.type === 'error'"
                 class="text-xs text-red-600 bg-red-50 border border-red-100 rounded-xl px-3 py-2">
              {{ msg.text }}
            </div>

            <!-- Thinking -->
            <div v-else-if="msg.type === 'thinking'" 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>

        <!-- Input -->
        <div class="p-3 border-t bg-gray-50">
          <Textarea v-model="promptInput" placeholder="Báo cáo doanh thu tháng này theo danh mục..."
                    class="min-h-[72px] text-xs resize-none mb-2"
                    @keydown.enter.prevent.exact="submit" />
          <div class="flex gap-2">
            <Button @click="submit" :disabled="sending || !promptInput.trim()" class="flex-1">
              {{ sending ? '⏳ Đang xử lý...' : '📊 Tạo báo cáo' }}
            </Button>
          </div>
        </div>
      </div>

      <!-- Report output -->
      <div class="flex-1 overflow-hidden flex flex-col">
        <div class="flex items-center px-4 py-2 border-b bg-gray-50">
          <h2 class="text-sm font-bold text-gray-700">📄 Báo cáo</h2>
          <button v-if="showReport" @click="window.print()"
                  class="ml-auto text-xs text-gray-500 hover:text-gray-800 border border-gray-200 px-2 py-0.5 rounded">
            📥 Xuất PDF
          </button>
        </div>
        <div class="flex-1 overflow-y-auto">
          <div v-if="!showReport" class="flex flex-col items-center justify-center h-full text-gray-400">
            <div class="text-5xl mb-3">📊</div>
            <p class="text-sm">Nhập câu hỏi bên trái để tạo báo cáo</p>
            <p class="text-xs mt-1 text-gray-300">Ví dụ: "Doanh thu theo danh mục tháng 3"</p>
          </div>
          <div v-else class="p-6" v-html="reportHtml"
               style="font-family: inherit; font-size: 14px; line-height: 1.6;"></div>
        </div>
      </div>
    </div>
  </DashboardLayout>
</template>
