<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import PageHeader from './components/mobile-page-header.vue'
import Preamble from './components/preamble.vue'
import MessageList from './components/message-list.vue'
import FooterInput from './components/footer-input.vue'
import { PersonalAppConfigState } from '@/store/types/personal-app-config'
import { useUserStore } from '@/store/modules/user'
import { defaultPersonalAppConfigState } from '@/store/modules/personal-app-config'
import { fetchCreateContinueQuestions, fetchCreateDialogues, fetchGetApplicationInfo } from '@/apis/agent-application'
import { useLayoutConfig } from '@/composables/useLayoutConfig'

const { t } = useI18n()

const router = useRouter()

const userStore = useUserStore()

const { isMobile } = useLayoutConfig()

const fullScreenLoading = ref(false)
const agentId = ref('')
const dialogsId = ref('')

const agentApplicationConfig = ref<PersonalAppConfigState>(defaultPersonalAppConfigState())

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'>('default')
const continueQuestionList = ref<string[]>([])

onMounted(async () => {
  if (router.currentRoute.value.params.agentId) {
    agentId.value = router.currentRoute.value.params.agentId as string
  }

  if (!isMobile.value) {
    router.replace({
      name: 'ShareWebApplication',
      params: { agentId: agentId.value },
    })
  }

  if (agentId.value) {
    fullScreenLoading.value = true
    await handleGetApplicationDetail()
    userStore.isLogin && (await handleCreateDialogues())
    fullScreenLoading.value = false
    return
  }

  router.replace({ name: 'Home' })
})

async function handleGetApplicationDetail() {
  fetchGetApplicationInfo<PersonalAppConfigState>(agentId.value)
    .then((res) => {
      agentApplicationConfig.value = res.data
      continuousQuestionStatus.value = res.data.commConfig.continuousQuestionStatus
      document.title = agentApplicationConfig.value.baseInfo.agentTitle
    })
    .catch(() => {
      router.replace({ name: 'Home' })
    })
}

async function handleCreateDialogues() {
  const res = await fetchCreateDialogues(agentId.value)

  if (res.code === 0) {
    dialogsId.value = res.data as string
  }
}

function handleToLoginPage() {
  router.push({
    name: 'Login',
    query: { redirect: encodeURIComponent(router.currentRoute.value.fullPath) },
  })
}

function handleCreateApplicationPage() {
  window.$dialog.info({
    title: t('share_agent_module.create_agent_dialogue_title'),
    content: t('share_agent_module.create_agent_dialogue_content'),
    positiveText: t('share_agent_module.create_agent_dialogue_positive_text'),
  })
}

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.$dialog.warning({
    title: t('common_module.dialogue_module.clear_message_dialog_title'),
    content: t('common_module.dialogue_module.clear_message_dialog_content'),
    negativeText: t('common_module.cancel_btn_text'),
    positiveText: t('common_module.confirm_btn_text'),
    onPositiveClick: () => {
      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) {
    continueQuestionList.value = res.data
    handleUpdatePageScroll()
  }
}

function handleResetContinueQuestionList() {
  continueQuestionList.value = []
}
</script>

<template>
  <div v-loading="fullScreenLoading" class="h-full w-full">
    <PageHeader
      :agent-title="agentApplicationConfig.baseInfo.agentTitle"
      @to-login="handleToLoginPage"
      @to-create-application="handleCreateApplicationPage"
    />

    <div class="flex h-[calc(100%-48px)] w-full flex-col bg-[#f2f5f9]">
      <div v-if="messageList.length === 0" class="w-full flex-1 overflow-auto px-4">
        <Preamble :agent-application-config="agentApplicationConfig" />
      </div>

      <div v-if="messageList.length > 0" class="flex w-full flex-1 flex-col overflow-hidden pt-5">
        <div class="flex-1 overflow-auto">
          <MessageList
            ref="messageListRef"
            :agent-application-config="agentApplicationConfig"
            :message-list="messageList"
            :continuous-question-status="continuousQuestionStatus"
            :continuous-question-list="continueQuestionList"
          />
        </div>
      </div>

      <div class="footer-operation px-4">
        <FooterInput
          ref="footerInputRef"
          :message-list="messageList"
          :dialogs-id="dialogsId"
          :agent-id="agentApplicationConfig.baseInfo.agentId"
          :continuous-question-status="continuousQuestionStatus"
          @add-message-item="handleAddMessageItem"
          @update-specify-message-item="handleUpdateSpecifyMessageItem"
          @delete-last-message-item="handleDeleteLastMessageItem"
          @update-page-scroll="handleUpdatePageScroll"
          @clear-all-message="handleClearAllMessage"
          @to-login="handleToLoginPage"
          @create-continue-questions="handleCreateContinueQuestions"
          @reset-continue-question-list="handleResetContinueQuestionList"
        />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.footer-operation {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}

@include custom-scrollbar(4px);
</style>
