<script setup lang="ts">
import { computed, h, onMounted, readonly, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import CustomIcon from '@/components/custom-icon/custom-icon.vue'
import { useUserStore } from '@/store/modules/user'
import { usePersonalAppConfigStore } from '@/store/modules/personal-app-config'
import { formatDateTime } from '@/utils/date-formatter'
import { fetchPublishApplication } from '@/apis/agent-application'

const { t } = useI18n()

const defaultAvatar = 'https://gsst-poe-sit.gz.bcebos.com/data/20240910/1725952917468.png'

interface Emits {
  (e: 'changeAgentAppTabKey', value: string): void
}

const emit = defineEmits<Emits>()

const router = useRouter()

const userStore = useUserStore()
const personalAppConfigStore = usePersonalAppConfigStore()

const avatarOptions = readonly([
  {
    label: () => h('span', {}, t('common_module.logout')),
    key: 'logout',
    icon: () => h(CustomIcon, { icon: 'teenyicons:logout-solid' }),
  },
])

const modifiedTime = ref(personalAppConfigStore.modifiedTime)

const isInitGetAgentAppDetail = ref(false)

const isUpdateAgentAppConfig = ref(false)

const currentAgentAppTabKey = ref('config')

const publishBtnLoading = ref(false)

const agentAppOptionList = [
  {
    value: 'config',
    label: 'common_module.config',
  },
  {
    value: 'publish',
    label: 'common_module.publish',
  },
]

const personalAppConfig = computed(() => personalAppConfigStore.$state)

const isShowModifiedTime = computed(() => {
  return isUpdateAgentAppConfig.value && personalAppConfigStore.baseInfo.agentId
})

const publishBtnText = computed(() => {
  return personalAppConfigStore.baseInfo.agentPublishStatus === 'publish'
    ? t('personal_space_module.agent_module.agent_setting_module.update_publish_btn_text')
    : t('personal_space_module.agent_module.agent_setting_module.publish_btn_text')
})

const isShowPublishBtn = computed(() => {
  return currentAgentAppTabKey.value === 'config'
})

const isAllowClickPublish = computed(() => {
  return personalAppConfigStore.baseInfo.agentId && personalAppConfigStore.baseInfo.agentPublishStatus === 'publish'
})

watch(
  () => personalAppConfig.value,
  () => {
    if (isInitGetAgentAppDetail.value) {
      isInitGetAgentAppDetail.value = false
      return
    }

    modifiedTime.value = new Date()
    !isUpdateAgentAppConfig.value && (isUpdateAgentAppConfig.value = true)
  },
  { deep: true },
)

watch(
  () => personalAppConfig.value.knowledgeConfig.knowledgeIds,
  (newVal) => {
    newVal && (isInitGetAgentAppDetail.value = true)
  },
  { once: true },
)

onMounted(() => {
  if (router.currentRoute.value.params.agentId) {
    isInitGetAgentAppDetail.value = true
  }

  if (router.currentRoute.value.query.tabKey) {
    currentAgentAppTabKey.value = router.currentRoute.value.query.tabKey as string
  }
})

function handleBackPreviousPage() {
  router.replace({ name: 'PersonalSpaceApp' })
}

function handleDropdownSelect(key: string) {
  switch (key) {
    case 'logout':
      userStore.logout().then(() => {
        router.push({ name: 'Login' })
      })
      break
  }
}

function handleSwtichAgentAppOption(currentTabKey: string) {
  if (!isAllowClickPublish.value) return

  currentAgentAppTabKey.value = currentTabKey

  router.replace({
    name: router.currentRoute.value.name as string,
    query: { tabKey: currentTabKey },
    params: { ...router.currentRoute.value.params },
  })

  emit('changeAgentAppTabKey', currentTabKey)
}

async function handlePublishApplication() {
  if (!personalAppConfig.value.baseInfo.agentTitle) {
    window.$message.warning(t('personal_space_module.agent_module.agent_setting_module.missing_agent_title_message'))
    return
  }

  publishBtnLoading.value = true

  const res = await fetchPublishApplication(personalAppConfig.value).finally(() => (publishBtnLoading.value = false))

  if (res.code === 0) {
    window.$message.success(t('common_module.publish_success_message'))

    currentAgentAppTabKey.value = 'publish'
    router.replace({
      name: router.currentRoute.value.name as string,
      query: { tabKey: 'publish' },
      params: { agentId: personalAppConfig.value.baseInfo.agentId },
    })

    personalAppConfig.value.baseInfo.agentPublishStatus = 'publish'

    emit('changeAgentAppTabKey', 'publish')
  }
}
</script>

<template>
  <header class="h-navbar flex w-full items-center justify-between bg-[#f2f5f9] px-5 shadow-[inset_0_-1px_#e8e9eb]">
    <div class="flex flex-1 items-center">
      <CustomIcon
        icon="weui:back-outlined"
        class="hover:text-theme-color mr-5 cursor-pointer outline-none"
        @click="handleBackPreviousPage"
      />

      <div class="flex flex-col items-start justify-center">
        <NPopover trigger="hover">
          <template #trigger>
            <span class="font-500 line-clamp-1 max-w-[200px] break-words text-base text-[#000]">
              {{ personalAppConfigStore.baseInfo.agentTitle }}
            </span>
          </template>
          <span>{{ personalAppConfigStore.baseInfo.agentTitle }}</span>
        </NPopover>

        <div class="flex items-center text-xs">
          <NPopover trigger="hover">
            <template #trigger>
              <span class="line-clamp-1 max-w-[200px] break-words text-[#84868c]">
                {{
                  personalAppConfigStore.baseInfo.agentDesc ||
                  t('personal_space_module.agent_module.agent_setting_module.missing_agent_desc_message')
                }}
              </span>
            </template>
            <span>
              {{
                personalAppConfigStore.baseInfo.agentDesc ||
                t('personal_space_module.agent_module.agent_setting_module.missing_agent_desc_message')
              }}
            </span>
          </NPopover>

          <div
            v-show="personalAppConfigStore.baseInfo.agentId"
            class="ml-3 h-5 rounded bg-white px-2 leading-5 text-[#5c5f66]"
          >
            {{ t('personal_space_module.agent_module.agent_setting_module.modified') }}
          </div>
          <div v-show="isShowModifiedTime" class="ml-3 h-5 rounded-md bg-white px-2 leading-5 text-[#151b26]">
            {{ t('personal_space_module.agent_module.agent_setting_module.auto_save_in') }}
            {{ formatDateTime(modifiedTime, 'HH:mm:ss') }}
          </div>
        </div>
      </div>
    </div>

    <div class="flex h-[38px] rounded-lg bg-[#e3e8f0] p-0.5">
      <div
        v-for="optionItem in agentAppOptionList"
        :key="optionItem.value"
        :value="optionItem.value"
        :label="optionItem.label"
        class="flex w-20 items-center justify-center rounded-lg"
        :class="[
          currentAgentAppTabKey === optionItem.value ? 'text-theme-color bg-white' : 'text-[#84868c]',
          isAllowClickPublish ? 'hover:text-theme-color cursor-pointer' : 'cursor-not-allowed',
        ]"
        @click="handleSwtichAgentAppOption(optionItem.value)"
      >
        <NPopover v-if="!isAllowClickPublish" trigger="hover">
          <template #trigger>
            {{ t(optionItem.label) }}
          </template>
          <span> {{ t('personal_space_module.agent_module.agent_setting_module.please_finish_publish') }}</span>
        </NPopover>
        <div v-if="isAllowClickPublish">{{ t(optionItem.label) }}</div>
      </div>
    </div>

    <div class="flex flex-1 items-center justify-end">
      <NButton
        v-show="isShowPublishBtn"
        type="primary"
        class="min-w-20!"
        :bordered="false"
        :disabled="!personalAppConfig.baseInfo.agentId"
        :loading="publishBtnLoading"
        @click="handlePublishApplication"
      >
        {{ publishBtnText }}
      </NButton>
      <NDropdown trigger="click" :options="avatarOptions" @select="handleDropdownSelect">
        <div class="ml-10 flex h-full cursor-pointer items-center">
          <NAvatar round :size="30" object-fit="cover" :src="userStore.userInfo.avatarUrl || defaultAvatar" />
        </div>
      </NDropdown>
    </div>
  </header>
</template>
