<template>
  <div class="flex flex-col h-[calc(100vh-8rem)]">
    <!-- Chat messages area -->
    <div ref="chatContainer" class="flex-1 overflow-y-auto p-4 pb-24 space-y-3">
      <div
        v-for="(message, idx) in chat"
        :key="idx"
        class="flex"
        :class="message.role === 'user' ? 'justify-end' : 'justify-start'"
      >
        <div
          class="max-w-[80%] lg:max-w-[70%] rounded-2xl px-4 py-3 shadow-sm"
          :class="message.role === 'user' ? 'bg-primary text-primary-content' : 'bg-base-100 text-base-content'"
        >
          <Text weight="semibold" class="mb-1">
            {{ message.role === 'user' ? t('aiAssistants.view.you') : t('aiAssistants.view.agentName') }}
          </Text>
          <Text :tone="message.role === 'user' ? undefined : 'muted'">
            {{ message.content }}
          </Text>
        </div>
      </div>
      <div v-if="isStreaming" class="text-sm text-base-content/60">
        {{ t('aiAssistants.view.typing') }}
      </div>
    </div>

    <!-- Input area fixed to bottom -->
    <div class="fixed bottom-0 left-0 right-0 border-t border-base-300 bg-base-100 p-4 z-30">
      <form class="flex items-end gap-3 px-4 lg:px-6" @submit.prevent="handleSend">
        <div class="flex-1">
          <Textarea
            v-model="input"
            :placeholder="t('aiAssistants.view.placeholder')"
            rows="2"
            class="w-full"
          />
        </div>
        <div class="flex items-center gap-2">
          <Button type="submit" :loading="isSending" :disabled="!input.trim()">
            {{ t('aiAssistants.view.send') }}
          </Button>
          <Button type="button" variant="ghost" @click="resetChat" :disabled="isSending">
            {{ t('aiAssistants.view.reset') }}
          </Button>
        </div>
      </form>
      <div class="text-sm text-error text-center mt-2" v-if="error">
        {{ error }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
definePageMeta({
  layout: 'topnav',
  middleware: ['auth-oidc']
})

const { t } = useI18n()
const runtimeConfig = useRuntimeConfig()

const agentUrl = computed(() => runtimeConfig.public.langAgentUrl || '')
const chatContainer = ref<HTMLElement | null>(null)
const chat = ref<{ role: 'user' | 'assistant', content: string }[]>([
  { role: 'assistant', content: t('aiAssistants.view.welcome') }
])
const input = ref('')
const isSending = ref(false)
const isStreaming = ref(false)
const error = ref('')

const scrollToBottom = () => {
  nextTick(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight
    }
  })
}

const handleSend = async () => {
  if (!input.value.trim()) return
  error.value = ''
  const userMessage = input.value.trim()
  chat.value.push({ role: 'user', content: userMessage })
  input.value = ''
  isSending.value = true
  isStreaming.value = true
  scrollToBottom()

  try {
    const body = {
      input: {
        messages: chat.value.map((m) => ({
          type: m.role === 'assistant' ? 'ai' : 'human',
          content: m.content
        }))
      }
    }

    const response = await $fetch(`${agentUrl.value}/invoke`, {
      method: 'POST',
      body
    })

    const outputMessages = (response as any)?.output?.messages || []
    const last = outputMessages[outputMessages.length - 1]
    const content = last?.content?.[0]?.text || last?.content || t('aiAssistants.view.emptyResponse')
    chat.value.push({ role: 'assistant', content })
    scrollToBottom()
  } catch (e: unknown) {
    console.error('Agent error', e)
    error.value = e instanceof Error ? e.message : t('aiAssistants.view.error')
    chat.value.push({ role: 'assistant', content: t('aiAssistants.view.error') })
    scrollToBottom()
  } finally {
    isSending.value = false
    isStreaming.value = false
  }
}

const resetChat = () => {
  chat.value = [{ role: 'assistant', content: t('aiAssistants.view.welcome') }]
  input.value = ''
  error.value = ''
}
</script>
