<script setup lang="ts">
import { computed, h, onMounted, readonly, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { DropdownOption } from 'naive-ui'
import { useI18n } from 'vue-i18n'
import { sidebarMenus } from '@/router/index'
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('sidebar_module.dropdown_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: 'personal_space_module.agent_module.agent_setting_module.agent_options_module.config',
  },
  {
    value: 'publish',
    label: 'personal_space_module.agent_module.agent_setting_module.agent_options_module.publish',
  },
]

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

const menuOptions = computed(() => {
  return sidebarMenus.map((item) => {
    return {
      label: item.label,
      key: item.key,
      routeName: item.routeName,
      icon: () => h(CustomIcon, { icon: item.icon || 'icon-home' }),
    }
  })
})

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 },
)

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 handleMenuSelect(_key: number, option: DropdownOption) {
  router.replace({ name: option.routeName as string })
}

function handleBackPreviousPage() {
  router.go(-1)
}

function handleDropdownSelect(key: number) {
  if (key === 1) {
    userStore.logout().then(() => {
      router.push({ name: 'Login' })
    })
  }
}

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">
      <NDropdown trigger="hover" :options="menuOptions" @select="handleMenuSelect">
        <CustomIcon
          icon="weui:back-outlined"
          class="hover:text-theme-color mr-5 outline-none"
          @click="handleBackPreviousPage"
        />
      </NDropdown>

      <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>
