<template>
  <aside
    class="fixed top-0 left-0 bottom-0 z-50 overflow-hidden transition-[width] duration-300"
    :style="{ width: open ? width : '0px' }"
    aria-label="AI assistant"
  >
    <div
      class="h-full flex flex-col bg-base-100/80 backdrop-blur-xl border-r border-white/10 shadow-xl transition-opacity duration-200"
      :class="open ? 'opacity-100' : 'opacity-0 pointer-events-none'"
    >
      <div class="flex items-center justify-between px-4 py-3 border-b border-white/10">
        <div class="flex items-center gap-2">
          <div class="w-8 h-8 rounded-full bg-primary/20 flex items-center justify-center">
            <Icon name="lucide:bot" size="16" class="text-primary" />
          </div>
          <div class="font-semibold text-base-content">{{ $t('aiAssistants.view.agentName') }}</div>
        </div>
        <button
          class="btn btn-ghost btn-xs btn-circle text-base-content/60 hover:text-base-content"
          aria-label="Close"
          @click="emit('close')"
        >
          <Icon name="lucide:x" size="14" />
        </button>
      </div>

      <div ref="chatContainer" class="flex-1 overflow-y-auto p-4 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-[90%] rounded-2xl px-3 py-2 shadow-sm"
            :class="message.role === 'user' ? 'bg-primary text-primary-content' : 'bg-base-100 text-base-content border border-base-300'"
          >
            <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>

      <div class="border-t border-base-300 bg-base-100/70 p-3">
        <form class="flex items-end gap-2" @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 flex-col gap-2">
            <Button type="submit" size="sm" :loading="isSending" :disabled="!input.trim()">
              {{ $t('aiAssistants.view.send') }}
            </Button>
            <Button type="button" size="sm" variant="ghost" @click="resetChat" :disabled="isSending">
              {{ $t('aiAssistants.view.reset') }}
            </Button>
          </div>
        </form>
        <div class="text-xs text-error text-center mt-2" v-if="error">
          {{ error }}
        </div>
      </div>
    </div>
  </aside>
</template>

<script setup lang="ts">
const props = defineProps<{
  open: boolean
  width: string
}>()

const emit = defineEmits<{
  (e: 'close'): void
}>()

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 = ''
}

watch(() => props.open, (isOpen) => {
  if (isOpen) scrollToBottom()
})
</script>
