<script setup lang="ts">
import { provide, useTemplateRef } from 'vue'
import { ScrollbarInst } from 'naive-ui'
import { useElementVisibility } from '@vueuse/core'
import MessageItem from './message-item.vue'
import type { MessageItemInterface } from '../types'

interface Props {
  messageList: Map<string, MessageItemInterface>
}

defineProps<Props>()

const emit = defineEmits<{
  showKnowledgeResult: [knowledgeContentResult: KnowledgeContentResultItem[]]
  updateSpecifyMessageItem: [messageId: string, newMessageItem: Partial<MessageItemInterface>]
}>()

const scrollbarRef = useTemplateRef<ScrollbarInst | null>('scrollbarRef')

const backBottomBtnFlagRef = useTemplateRef<HTMLDivElement | null>('backBottomBtnFlagRef')

const isNotShowBackBottomBtn = useElementVisibility(backBottomBtnFlagRef)

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

function scrollToBottom() {
  if (scrollbarRef.value) {
    scrollbarRef.value.scrollTo({ top: 999999999, behavior: 'smooth' })
  }
}

defineExpose({
  scrollToBottom,
  isNotShowBackBottomBtn,
})
</script>

<template>
  <div class="relative flex-1 overflow-hidden overflow-y-auto py-[20px]">
    <n-scrollbar ref="scrollbarRef" class="min-h-full" content-class="min-h-full flex">
      <div class="relative flex flex-col-reverse overflow-hidden">
        <div class="pr-[10px]">
          <MessageItem
            v-for="[key, messageItem] in messageList"
            :key="key"
            :message-item-id="key"
            :message-item="messageItem"
            @show-knowledge-result="emit('showKnowledgeResult', messageItem.knowledgeContentResult)"
          />
        </div>
        <div ref="backBottomBtnFlagRef" class="-z-1 absolute bottom-0 h-[100px] w-full"></div>
      </div>
    </n-scrollbar>

    <Transition name="back-bottom-btn" mode="out-in">
      <div
        v-show="!isNotShowBackBottomBtn"
        class="absolute bottom-[30px] right-[30px] text-end"
        style="translate: calc(-50% + 30px)"
      >
        <button
          class="flex-center flex-center hover:text-theme-color inline-flex h-[26px] w-[26px] rounded-full border bg-white"
          @click.stop="scrollToBottom"
        >
          <i class="iconfont icon-huidaodibu text-[12px]" />
        </button>
      </div>
    </Transition>
  </div>
</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>
