<script setup lang="ts">
import { computed, inject, onMounted, onUnmounted, ref } from 'vue'
import { Emitter } from 'mitt'
import { useI18n } from 'vue-i18n'
import { fetchCustomEventSource } from '@/composables/useEventSource'
import { usePersonalAppConfigStore } from '@/store/modules/personal-app-config'

interface Props {
  messageList: ConversationMessageItem[]
  continuousQuestionStatus: 'default' | 'close'
}

const { t } = useI18n()

const props = defineProps<Props>()

const emit = defineEmits<{
  addMessageItem: [value: ConversationMessageItem]
  updateSpecifyMessageItem: [messageItemIndex: number, newObj: Partial<ConversationMessageItem>]
  deleteLastMessageItem: []
  updatePageScroll: []
  clearAllMessage: []
  createContinueQuestions: [value: string]
  updateContinuousQuestionStatus: [value: 'default' | 'close']
}>()

const personalAppConfigStore = usePersonalAppConfigStore()

const emitter = inject<Emitter<MittEvents>>('emitter')

const inputMessageContent = ref('')

const isAnswerResponseWait = ref(false)

let controller: AbortController | null = null

const agentId = computed(() => {
  return personalAppConfigStore.baseInfo.agentId
})

const isCreateContinueQuestions = computed(() => {
  return props.continuousQuestionStatus === 'default'
})

const isAllowClearMessage = computed(() => {
  return props.messageList.length > 0
})

const isSendBtnDisabled = computed(() => {
  return !inputMessageContent.value.trim()
})

onUnmounted(() => {
  blockMessageResponse()
  emitter?.off('selectQuestion')
})

onMounted(() => {
  emitter?.on('selectQuestion', (featuredQuestion) => {
    inputMessageContent.value = featuredQuestion
    handleMessageSend()
  })
})

function messageItemFactory() {
  return {
    timestamp: Date.now(),
    role: 'user',
    textContent: '',
    isEmptyContent: false,
    isTextContentLoading: false,
    isAnswerResponseLoading: false,
  } as const
}

function handleEnterKeypress(event: KeyboardEvent) {
  if (event.code === 'Enter' && !event.shiftKey) {
    event.preventDefault()

    if (!inputMessageContent.value.trim() || isAnswerResponseWait.value) return ''

    handleMessageSend()
  }
}

function handleMessageSend() {
  if (!inputMessageContent.value.trim() || isAnswerResponseWait.value) return ''

  const messages: {
    content: {
      type: string
      text: string
      image_url: {
        url: ''
      }
    }[]
    role: string
  }[] = []

  emit('updateContinuousQuestionStatus', personalAppConfigStore.commConfig.continuousQuestionStatus)
  emit('addMessageItem', { ...messageItemFactory(), textContent: inputMessageContent.value })
  emit('updatePageScroll')

  props.messageList.forEach((messageItem) => {
    messages.push({
      content: [
        {
          type: 'text',
          text: messageItem.textContent,
          image_url: {
            url: '',
          },
        },
      ],
      role: messageItem.role,
    })
  })

  inputMessageContent.value = ''
  isAnswerResponseWait.value = true

  emit('addMessageItem', {
    ...messageItemFactory(),
    role: 'assistant',
    isTextContentLoading: true,
    isAnswerResponseLoading: true,
  })
  emit('updatePageScroll')

  const currentMessageIndex = props.messageList.length - 1
  let replyTextContent = ''

  controller = new AbortController()

  fetchCustomEventSource({
    path: '/api/rest/agentApplicationInfoRest/preview.json',
    payload: {
      agentId: agentId.value,
      messages,
    },
    controller,
    onMessage: (data: any) => {
      if (data === '[DONE]') {
        emit('updateSpecifyMessageItem', currentMessageIndex, {
          isEmptyContent: !replyTextContent,
          isTextContentLoading: false,
          isAnswerResponseLoading: false,
        })
        isCreateContinueQuestions.value && emit('createContinueQuestions', replyTextContent)
        emit('updatePageScroll')
        blockMessageResponse()
        return
      }

      if (data) {
        replyTextContent += data

        emit('updateSpecifyMessageItem', currentMessageIndex, {
          textContent: replyTextContent,
          isTextContentLoading: false,
        })
        emit('updatePageScroll')
      }
    },
    onRequestError: () => {
      errorMessageResponse()
    },
    onError: () => {
      errorMessageResponse()
    },
    onFinally: () => {
      controller = null
    },
  })
}

function errorMessageResponse() {
  emit('updateSpecifyMessageItem', props.messageList.length - 1, {
    isTextContentLoading: false,
    textContent: '',
  })
  emit('deleteLastMessageItem')
  emit('deleteLastMessageItem')
  blockMessageResponse()
}

function handleClearAllMessage() {
  if (!isAllowClearMessage.value) return

  emit('clearAllMessage')
}

function blockMessageResponse() {
  controller?.abort()
  isAnswerResponseWait.value = false
}

defineExpose({
  blockMessageResponse,
})
</script>

<template>
  <div class="mb-3 mt-5 px-5">
    <div class="flex">
      <div class="mr-2 flex h-8 w-8 items-center justify-center">
        <NPopover trigger="hover">
          <template #trigger>
            <i
              class="iconfont icon-clear text-base leading-none"
              :class="
                isAllowClearMessage
                  ? 'hover:text-theme-color cursor-pointer text-[#5c5f66]'
                  : 'cursor-not-allowed text-[#b8babf]'
              "
              @click="handleClearAllMessage"
            />
          </template>
          <span class="text-xs">
            {{ t('common_module.dialogue_module.clear_message_popover_message') }}
          </span>
        </NPopover>
      </div>

      <div class="relative flex-1">
        <NInput
          v-model:value="inputMessageContent"
          :placeholder="t('common_module.dialogue_module.question_input_placeholder')"
          class="rounded-xl! shadow-[0_1px_#09122105,0_1px_1px_#09122105,0_3px_3px_#09122103,0_9px_9px_#09122103]! py-[4px] pr-[50px]"
          @keypress="handleEnterKeypress"
        />
        <div
          class="bg-px-send-png absolute bottom-2 right-[20px] h-[24px] w-[24px]"
          :class="isSendBtnDisabled || isAnswerResponseWait ? 'opacity-60' : 'cursor-pointer'"
          @click="handleMessageSend"
        />
      </div>
    </div>

    <div class="mt-[9px] pl-10">
      <span class="text-xs text-[#84868c]">
        {{ t('common_module.dialogue_module.generate_warning_message') }}
      </span>
    </div>
  </div>
</template>
