<script setup lang="ts">
import { computed, nextTick, provide, ref, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useElementVisibility } from '@vueuse/core'
import MessageItem from './message-item.vue'
import ContinueQuestion from './continue-question.vue'
import { useScroll } from '@/composables/useScroll'
import { PersonalAppConfigState } from '@/store/types/personal-app-config'
import { useLayoutConfig } from '@/composables/useLayoutConfig'
import HitKnowledge from '@/views/personal-space/personal-app-setting/components/agent-config/agent-preview/components/hit-knowledge.vue'

interface Props {
  messageList: Map<string, ConversationMessageItem>
  agentApplicationConfig: PersonalAppConfigState
  continuousQuestionStatus: 'default' | 'close'
  continuousQuestionList: string[]
  isAnswerResponseLoading: boolean
  createContinueQuestionsException: boolean
  isAnswerResponseInterrupt?: boolean
}

const props = defineProps<Props>()

const emit = defineEmits<{
  audioPlay: [messageItem: ConversationMessageItem]
  audioPause: []
  updateSpecifyMessageItem: [messageId: string, newMessageItem: Partial<ConversationMessageItem>]
}>()

const { t } = useI18n()

const { isMobile } = useLayoutConfig()

const { scrollRef, scrollToBottom } = useScroll()
const backBottomBtnFlagRef = useTemplateRef<HTMLDivElement | null>('backBottomBtnFlagRef')
const isNotShowBackBottomBtn = useElementVisibility(backBottomBtnFlagRef)

provide('updateSpecifyMessageItem', {
  updateSpecifyMessageItem: (messageId: string, newMessageItem: Partial<ConversationMessageItem>) => {
    emit('updateSpecifyMessageItem', messageId, newMessageItem)
  },
})

const isShowKnowledgeContent = ref(false)
const currentKnowledgeContentResult = ref<KnowledgeContentResultItem[]>([])

const isShowContinueQuestion = computed(() => {
  return (
    props.continuousQuestionStatus === 'default' &&
    props.messageList.size > 1 &&
    !props.isAnswerResponseLoading &&
    !props.createContinueQuestionsException &&
    !props.isAnswerResponseInterrupt
  )
})

watch(
  () => props.messageList.size,
  () => {
    clickBackBottom()
  },
)

defineExpose({
  scrollToBottom: handleScrollToBottom,
})

function clickBackBottom() {
  scrollToBottom()
}

function handleScrollToBottom() {
  nextTick(() => {
    isNotShowBackBottomBtn.value && scrollToBottom()
  })
}

function handleShowKnowledgeResult(knowledgeContentResult: KnowledgeContentResultItem[]) {
  isShowKnowledgeContent.value = true
  currentKnowledgeContentResult.value = knowledgeContentResult
}
</script>

<template>
  <main ref="scrollRef" class="h-full overflow-y-auto overflow-x-hidden px-5">
    <div class="relative">
      <MessageItem
        v-for="[key, messageItem] in messageList"
        :key="key"
        :message-item-id="key"
        :message-item="messageItem"
        :agent-application-config="agentApplicationConfig"
        @audio-play="() => $emit('audioPlay', messageItem)"
        @audio-pause="() => $emit('audioPause')"
        @show-knowledge-result="handleShowKnowledgeResult(messageItem.knowledgeContentResult)"
      />

      <p v-show="isMobile && isAnswerResponseLoading" class="ml-1 mt-[7px] text-xs text-[#84868c]">
        {{ t('common_module.dialogue_module.do_not_exit_page') }}
      </p>

      <div v-show="isShowContinueQuestion">
        <ContinueQuestion :continuous-question-list="continuousQuestionList" />
      </div>

      <div ref="backBottomBtnFlagRef" class="-z-1 absolute bottom-0 h-[100px] w-full"></div>
    </div>

    <Transition name="back-bottom-btn" mode="out-in">
      <div
        v-show="!isNotShowBackBottomBtn"
        class="flex-center hover:text-theme-color absolute bottom-5 right-5 h-6 w-6 cursor-pointer rounded-full bg-white shadow-[0_0_0_1px_#ededed]"
        @click.stop="clickBackBottom"
      >
        <i class="iconfont icon-huidaodibu text-sm" />
      </div>
    </Transition>

    <HitKnowledge
      v-model:is-show-drawer="isShowKnowledgeContent"
      :knowledge-content-result="currentKnowledgeContentResult!"
      :to="'#share-agent-web-container'"
    />
  </main>
</template>

<style lang="scss" scoped>
.back-bottom-btn-enter-active,
.back-bottom-btn-leave-active {
  transition-timing-function: ease-in-out;
  transition-duration: 0.2s;
  transition-property: opacity;
}

.back-bottom-btn-enter-from,
.back-bottom-btn-leave-to {
  opacity: 0;
}
</style>
