<script setup lang="ts">
import { ref, nextTick, watch } from 'vue'
import { useConversationsStore } from '../../stores/conversations'
import { useChatStore } from '../../stores/chat'
import MessageBubble from './MessageBubble.vue'
import ChatInput from './ChatInput.vue'
import StreamingIndicator from './StreamingIndicator.vue'

const convStore = useConversationsStore()
const chatStore = useChatStore()
const messagesContainer = ref<HTMLElement | null>(null)
const payloadExpanded = ref(false)

function scrollToBottom() {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

watch(() => convStore.messages.length, scrollToBottom)
watch(() => chatStore.streamingContent, scrollToBottom)
watch(() => chatStore.pendingConfirmation, scrollToBottom)

async function handleSend(question: string) {
  if (!convStore.currentConversationId) {
    await convStore.createConversation(question.slice(0, 80))
  }
  chatStore.sendQuestion(question)
}
</script>

<template>
  <div class="flex flex-col h-full">
    <!-- Messages -->
    <div ref="messagesContainer" class="flex-1 overflow-y-auto px-4 py-6">
      <div class="max-w-4xl mx-auto space-y-4">
        <!-- Empty state -->
        <div v-if="convStore.messages.length === 0 && !chatStore.isStreaming" class="text-center py-20">
          <h2 class="text-2xl font-bold text-dark-300 mb-2">Welcome to V3Q.AI</h2>
          <p class="text-dark-500 mb-6">Ask a question about your business data</p>
          <div class="flex flex-wrap justify-center gap-2">
            <button
              v-for="q in [
                'How many orders were placed this month?',
                'Show me the top 10 customers by revenue',
                'What products have low stock?'
              ]"
              :key="q"
              @click="handleSend(q)"
              class="px-4 py-2 bg-dark-800 border border-dark-600 rounded-lg text-sm text-dark-300 hover:bg-dark-700 hover:text-dark-100 transition-colors"
            >{{ q }}</button>
          </div>
        </div>

        <!-- Messages -->
        <MessageBubble
          v-for="msg in convStore.messages"
          :key="msg.id"
          :message="msg"
        />

        <!-- Confirmation dialog -->
        <div v-if="chatStore.pendingConfirmation" class="flex gap-3">
          <div class="w-8 h-8 rounded-full bg-yellow-600 flex items-center justify-center shrink-0 text-xs font-bold">!</div>
          <div class="flex-1 bg-dark-800 border border-yellow-600/40 rounded-lg p-4">
            <!-- API confirmation -->
            <template v-if="chatStore.pendingConfirmation.type === 'api'">
              <h4 class="text-yellow-400 font-semibold text-sm mb-2">Confirm API Call</h4>
              <p class="text-dark-300 text-sm mb-2">{{ chatStore.pendingConfirmation.description }}</p>
              <p v-if="chatStore.pendingConfirmation.metadataPreview" class="text-dark-500 text-xs mb-3">{{ chatStore.pendingConfirmation.metadataPreview }}</p>

              <!-- Full payload preview -->
              <div v-if="chatStore.pendingConfirmation.fullPayload" class="mb-4">
                <button
                  @click="payloadExpanded = !payloadExpanded"
                  class="text-xs text-primary-400 hover:text-primary-300 mb-2 flex items-center gap-1"
                >
                  <span class="font-mono">{{ payloadExpanded ? '▼' : '▶' }}</span>
                  {{ payloadExpanded ? 'Hide' : 'Show' }} exact payload
                </button>

                <div v-if="payloadExpanded" class="space-y-2">
                  <!-- System prompt (schema context) -->
                  <div>
                    <span class="text-dark-500 text-xs font-semibold block mb-1">SYSTEM PROMPT (schema metadata):</span>
                    <pre class="bg-dark-900 border border-dark-600 rounded p-3 text-xs text-dark-400 whitespace-pre-wrap max-h-80 overflow-y-auto font-mono">{{ chatStore.pendingConfirmation.fullPayload.system_prompt }}</pre>
                  </div>

                  <!-- User message -->
                  <div>
                    <span class="text-dark-500 text-xs font-semibold block mb-1">USER MESSAGE:</span>
                    <pre class="bg-dark-900 border border-dark-600 rounded p-3 text-xs text-blue-400 whitespace-pre-wrap font-mono">{{ chatStore.pendingConfirmation.fullPayload.user_message }}</pre>
                  </div>

                  <!-- Feedback (retry only) -->
                  <div v-if="chatStore.pendingConfirmation.fullPayload.feedback">
                    <span class="text-dark-500 text-xs font-semibold block mb-1">ERROR FEEDBACK:</span>
                    <pre class="bg-dark-900 border border-dark-600 rounded p-3 text-xs text-orange-400 whitespace-pre-wrap font-mono">{{ chatStore.pendingConfirmation.fullPayload.feedback }}</pre>
                  </div>

                  <!-- Conversation history -->
                  <div v-if="chatStore.pendingConfirmation.fullPayload.conversation_history?.length">
                    <span class="text-dark-500 text-xs font-semibold block mb-1">CONVERSATION HISTORY ({{ chatStore.pendingConfirmation.fullPayload.conversation_history.length }} messages):</span>
                    <div class="bg-dark-900 border border-dark-600 rounded p-3 max-h-40 overflow-y-auto space-y-2">
                      <div v-for="(msg, i) in chatStore.pendingConfirmation.fullPayload.conversation_history" :key="i" class="text-xs font-mono">
                        <span :class="msg.role === 'user' ? 'text-blue-400' : 'text-green-400'">{{ msg.role }}:</span>
                        <span class="text-dark-400 ml-1">{{ msg.content }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </template>

            <!-- SQL confirmation -->
            <template v-if="chatStore.pendingConfirmation.type === 'sql'">
              <h4 class="text-yellow-400 font-semibold text-sm mb-2">
                Confirm SQL Execution
                <span v-if="(chatStore.pendingConfirmation.attempt ?? 1) > 1" class="text-yellow-600 font-normal">
                  (retry #{{ chatStore.pendingConfirmation.attempt }})
                </span>
              </h4>
              <p class="text-dark-300 text-sm mb-2">{{ chatStore.pendingConfirmation.description }}</p>
              <div v-if="chatStore.pendingConfirmation.tables?.length" class="mb-2">
                <span class="text-dark-500 text-xs">Tables: </span>
                <span v-for="t in chatStore.pendingConfirmation.tables" :key="t" class="inline-block bg-dark-700 text-dark-300 text-xs rounded px-2 py-0.5 mr-1">{{ t }}</span>
              </div>
              <pre v-if="chatStore.pendingConfirmation.query" class="bg-dark-900 border border-dark-600 rounded p-3 text-xs text-green-400 whitespace-pre-wrap mb-4 max-h-60 overflow-y-auto font-mono">{{ chatStore.pendingConfirmation.query }}</pre>
            </template>

            <div class="flex gap-3">
              <button @click="chatStore.approveConfirmation()" class="px-4 py-1.5 bg-green-600 hover:bg-green-500 text-white text-sm rounded font-medium transition-colors">
                Approve
              </button>
              <button @click="chatStore.rejectConfirmation()" class="px-4 py-1.5 bg-dark-600 hover:bg-red-700 text-dark-300 hover:text-white text-sm rounded font-medium transition-colors">
                Reject
              </button>
            </div>
          </div>
        </div>

        <!-- Streaming response -->
        <div v-if="chatStore.isStreaming && !chatStore.pendingConfirmation" class="flex gap-3">
          <div class="w-8 h-8 rounded-full bg-primary-600 flex items-center justify-center shrink-0 text-xs font-bold">AI</div>
          <div class="flex-1">
            <StreamingIndicator
              :content="chatStore.streamingContent"
              :status="chatStore.statusMessage"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- Input -->
    <ChatInput @send="handleSend" :disabled="chatStore.isStreaming" />
  </div>
</template>
