<script setup lang="ts">
import { computed, h, onMounted, readonly, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { storeToRefs } from 'pinia'
import { Left, Logout } from '@icon-park/vue-next'
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 { baseInfo } = storeToRefs(personalAppConfigStore)

const avatarOptions = readonly([
  {
    label: () => h('span', {}, t('common_module.logout')),
    key: 'logout',
    icon: () => h(Logout, { strokeWidth: 3, fill: '#333', theme: 'outline' }),
  },
])

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',
  },
  {
    value: 'analysis',
    label: 'common_module.analysis',
  },
]

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(
  () => personalAppConfigStore.$state,
  () => {
    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 handleBackPreviousPage() {
  router.back()
}

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

function handleSwitchAgentAppOption(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 (!baseInfo.value.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(personalAppConfigStore.$state).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: baseInfo.value.agentId },
    })

    baseInfo.value.agentPublishStatus = 'publish'

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

<template>
  <header class="h-navbar flex w-full items-center justify-between bg-[#F3F5F8] px-5 shadow-[inset_0_-1px_#e8e9eb]">
    <div class="flex flex-1 items-center">
      <div
        class="rounded-theme hover:bg-hover-background-color flex-center ml-[-8px] mr-3 h-7 w-7 cursor-pointer"
        @click="handleBackPreviousPage"
      >
        <Left theme="outline" size="20" fill="#333" class="mt-0.5" />
      </div>

      <div class="flex flex-col items-start justify-center">
        <n-ellipsis class="max-w-[200px]! text-base text-[#000]" :tooltip="{ width: '240px' }">
          <span>
            {{ personalAppConfigStore.baseInfo.agentTitle }}
          </span>
        </n-ellipsis>

        <div class="flex items-center text-xs">
          <n-ellipsis class="max-w-[200px]! text-[#84868c]" :tooltip="{ width: '240px' }">
            <span>
              {{
                personalAppConfigStore.baseInfo.agentDesc ||
                t('personal_space_module.agent_module.agent_setting_module.missing_agent_desc_message')
              }}
            </span>
          </n-ellipsis>

          <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="handleSwitchAgentAppOption(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="!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>
