<script setup lang="ts">
import { inject, onMounted, onUnmounted, ref } from 'vue'
import Preamble from './preamble.vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { Emitter } from 'mitt'
import MessageList from './message-list.vue'
import FooterInput from './footer-input.vue'
import { fetchCreateContinueQuestions } from '@/apis/agent-application'
import { usePersonalAppConfigStore } from '@/store/modules/personal-app-config'
import { Brain, Down } from '@icon-park/vue-next'
import MemoryPreviewModal from './memory-preview-modal.vue'

const { t } = useI18n()

const router = useRouter()

const personalAppConfigStore = usePersonalAppConfigStore()

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

const messageListRef = ref<InstanceType<typeof MessageList> | null>(null)
const footerInputRef = ref<InstanceType<typeof FooterInput> | null>(null)

const messageList = ref<ConversationMessageItem[]>([])

const continuousQuestionStatus = ref<'default' | 'close'>(personalAppConfigStore.commConfig.continuousQuestionStatus)

const continuousQuestionList = ref<string[]>([])
const isShowMemoryPreviewModal = ref(false)
const selectedMemoryTabName = ref('memoryVariable')

onMounted(() => {
  emitter?.on('resetAgent', () => {
    footerInputRef.value?.blockMessageResponse()
    messageList.value = []
  })
})

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

function handleAddMessageItem(messageItem: ConversationMessageItem) {
  messageList.value.push(messageItem)
}

function handleUpdateSpecifyMessageItem(messageItemIndex: number, newObj: Partial<ConversationMessageItem>) {
  if (messageList.value[messageItemIndex]) {
    Object.entries(newObj).forEach(([k, v]) => {
      ;(messageList.value[messageItemIndex] as any)[k as keyof typeof newObj] = v
    })
  }
}

function handleDeleteLastMessageItem() {
  messageList.value.pop()
}

function handleUpdatePageScroll() {
  messageListRef.value?.scrollToBottom()
}

function handleClearAllMessage() {
  window.$message
    .ctWarning(
      t('common_module.dialogue_module.clear_message_dialog_content'),
      t('common_module.dialogue_module.clear_message_dialog_title'),
    )
    .then(() => {
      footerInputRef.value?.blockMessageResponse()
      messageList.value = []
      window.$message.success(t('common_module.clear_success_message'))
    })
}

async function handleCreateContinueQuestions(replyTextContent: string) {
  const res = await fetchCreateContinueQuestions<string[]>({ input: replyTextContent })

  if (res.code === 0) {
    continuousQuestionList.value = res.data
    handleUpdatePageScroll()
  }
}

function handleUpdateContinueQuestionStatus(status: 'default' | 'close') {
  continuousQuestionStatus.value = status
  continuousQuestionList.value = []
}

function handleTurnMultiModelDialogue() {
  if (!personalAppConfigStore.baseInfo.agentId) return

  router.push({
    name: 'MultiModelDialogue',
    params: {
      agentId: personalAppConfigStore.baseInfo.agentId,
    },
  })
}

function handleOpenMemoryPreviewModal(MemoryTabName: string) {
  selectedMemoryTabName.value = MemoryTabName
  isShowMemoryPreviewModal.value = true
}
</script>

<template>
  <div class="flex h-full min-w-[300px] flex-[2_2_0%] flex-col overflow-hidden bg-[#f2f5f9]">
    <div class="flex items-center justify-between">
      <div class="mb-[18px] flex w-full items-center justify-between px-5 py-[18px]">
        <p class="text-base">
          {{ t('personal_space_module.agent_module.agent_setting_module.agent_config_module.preview') }}
        </p>

        <div class="flex items-center">
          <div
            :class="
              personalAppConfigStore.baseInfo.agentId
                ? 'text-font-color hover:text-theme-color cursor-pointer'
                : 'text-gray-font-color cursor-not-allowed'
            "
            @click="handleTurnMultiModelDialogue"
          >
            <i class="iconfont icon-moxing mr-1 text-sm" />
            <span>{{ t('common_module.multi_model_debug') }}</span>
          </div>

          <div
            v-show="
              personalAppConfigStore.commConfig.variableStructure !== null ||
              personalAppConfigStore.commConfig.isLongMemory === 'Y'
            "
            class="cursor-pointer"
          >
            <n-popover placement="bottom" trigger="hover" class="p-[4px]!" :show-arrow="false">
              <template #trigger>
                <div class="flex items-center justify-center pl-5 text-[14px]">
                  <Brain theme="outline" size="15" fill="#333" />
                  <div class="mx-[4px]">
                    {{ t('personal_space_module.agent_module.agent_setting_module.agent_config_module.memory') }}
                  </div>
                  <Down theme="outline" size="15" fill="#333" class="mt-[2px] inline" />
                </div>
              </template>
              <div>
                <div
                  v-show="personalAppConfigStore.commConfig.variableStructure !== null"
                  class="cursor-pointer px-[8px] py-[5px] hover:bg-[#f2f5f9]"
                  @click="handleOpenMemoryPreviewModal('memoryVariable')"
                >
                  {{ t('personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_variable') }}
                </div>
                <div
                  v-show="personalAppConfigStore.commConfig.isLongMemory === 'Y'"
                  class="cursor-pointer px-[8px] py-[5px] hover:bg-[#f2f5f9]"
                  @click="handleOpenMemoryPreviewModal('memoryFragment')"
                >
                  {{ t('personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_fragment') }}
                </div>
              </div>
            </n-popover>
          </div>
        </div>
      </div>
    </div>

    <div class="flex w-full flex-1 overflow-hidden">
      <div v-show="messageList.length === 0" class="flex w-full">
        <Preamble />
      </div>

      <div v-show="messageList.length > 0" class="w-full">
        <MessageList
          ref="messageListRef"
          :message-list="messageList"
          :continuous-question-status="continuousQuestionStatus"
          :continuous-question-list="continuousQuestionList"
        />
      </div>
    </div>

    <FooterInput
      ref="footerInputRef"
      :continuous-question-status="continuousQuestionStatus"
      :message-list="messageList"
      @add-message-item="handleAddMessageItem"
      @update-specify-message-item="handleUpdateSpecifyMessageItem"
      @delete-last-message-item="handleDeleteLastMessageItem"
      @update-page-scroll="handleUpdatePageScroll"
      @clear-all-message="handleClearAllMessage"
      @create-continue-questions="handleCreateContinueQuestions"
      @update-continuous-question-status="handleUpdateContinueQuestionStatus"
    />

    <MemoryPreviewModal v-model="isShowMemoryPreviewModal" :data="selectedMemoryTabName" />
  </div>
</template>

<style scoped lang="scss">
@include custom-scrollbar(6px);
</style>
