<script setup lang="ts">
import { computed, nextTick, watch } from 'vue'
import { useI18n } from 'vue-i18n'
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 { useBackBottom } from '@/composables/useBackBottom'
import { useLayoutConfig } from '@/composables/useLayoutConfig'

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

const props = defineProps<Props>()

defineEmits<{
  audioPlay: [messageItem: ConversationMessageItem]
  audioPause: []
}>()

const { t } = useI18n()

const { isMobile } = useLayoutConfig()

const { scrollRef, scrollToBottom } = useScroll()

const { visible, clickBackBottom, throttleScrollContainer } = useBackBottom(scrollRef, scrollToBottom)

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 handleScrollToBottom() {
  nextTick(() => {
    !visible.value && scrollToBottom()
  })
}
</script>

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

    <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
      v-show="visible"
      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-left rotate-270 text-sm" />
    </div>
  </main>
</template>
