<script setup lang="ts">
import { ref, watch } from 'vue'
import { Search } from '@icon-park/vue-next'
import {
  fetchGetApplicationList,
  fetchGetDebugApplicationInfo,
  fetchSaveAgentApplication,
} from '@/apis/agent-application'
import { useI18n } from 'vue-i18n'
import type { PersonalAppConfigState } from '@/store/types/personal-app-config'
import { useRouter } from 'vue-router'

interface Props {
  currentSelectPluginId: string
}

interface ApplicationInfoInterface {
  agentId: string
  agentTitle: string
  agentAvatar: string
  agentDesc: string
}

interface ApplicationItemInfoInterface {
  baseInfo: ApplicationInfoInterface
  unitIds: string[]
}

defineProps<Props>()
const showModal = defineModel<boolean>('showModal', { default: false })

const { t } = useI18n()
const router = useRouter()

const searchKeyword = ref('')
const applicationList = ref<ApplicationInfoInterface[]>([])
const getApplicationListLoading = ref(true)
const currentApplicationPluginOperationLoading = ref('')

watch(showModal, (newVal) => {
  newVal && getApplicationList()
})

function getApplicationList() {
  getApplicationListLoading.value = true

  fetchGetApplicationList<ApplicationItemInfoInterface[]>({ query: searchKeyword.value.trim(), publishStatus: '' })
    .then((res) => {
      if (res.code !== 0) return ''

      if (res.data) {
        const applicationListDraft: ApplicationInfoInterface[] = res.data.map((itemInfo) => {
          return {
            agentId: itemInfo.baseInfo.agentId,
            agentTitle: itemInfo.baseInfo.agentTitle,
            agentAvatar: itemInfo.baseInfo.agentAvatar,
            agentDesc: itemInfo.baseInfo.agentDesc,
            unitIds: itemInfo.unitIds || [],
          }
        })

        applicationList.value = applicationListDraft
      }
    })
    .finally(() => {
      getApplicationListLoading.value = false
    })
}

function handleSearchApplication() {
  if (!searchKeyword.value.trim()) {
    window.$message.warning(t('common_module.search_keyword_empty_tip'))
    return
  }

  getApplicationList()
}

function handleSearchAppKeywordClear() {
  searchKeyword.value = ''

  getApplicationList()
}

function handleAppAddPlugin(agentId: string) {
  currentApplicationPluginOperationLoading.value = agentId

  fetchGetDebugApplicationInfo<PersonalAppConfigState>(agentId)
    .then((res) => {
      if (res.code !== 0) return ''

      const payload = { ...res.data, unitIds: [...(res.data.unitIds || []), agentId] }

      fetchSaveAgentApplication(payload)
        .then((SaveRes) => {
          if (SaveRes.code !== 0) return ''

          getApplicationList()

          window.$message.success(t('common_module.successful_update'))

          router.push({ name: 'PersonalAppSetting', params: { agentId } })
        })
        .finally(() => {
          currentApplicationPluginOperationLoading.value = ''
        })
    })
    .catch(() => {
      currentApplicationPluginOperationLoading.value = ''
    })
}

function handleCreateNewApplication() {
  router.push({ name: 'PersonalAppSetting' })
}

function handleNavigateToAppSetting(agentId: string) {
  router.push({ name: 'PersonalAppSetting', params: { agentId } })
}
</script>

<template>
  <n-modal
    v-model:show="showModal"
    preset="card"
    :title="t('plugin_center_module.select_application')"
    :bordered="false"
    class="!w-[800px]"
    content-style="padding-right: 0;"
  >
    <div class="pr-[10px]">
      <div class="flex items-center justify-end pr-[14px]">
        <n-input
          v-model:value="searchKeyword"
          type="text"
          :placeholder="t('common_module.search')"
          class="!w-[300px]"
          clearable
          :on-clear="handleSearchAppKeywordClear"
          @keyup.enter="handleSearchApplication"
        >
          <template #prefix>
            <Search theme="outline" size="16" fill="#999" :stroke-width="3" />
          </template>
        </n-input>
        <n-button type="primary" class="!ml-[19px]" @click="handleCreateNewApplication">
          {{ t('plugin_center_module.create_new_application') }}
        </n-button>
      </div>

      <div v-show="!getApplicationListLoading" class="mt-[22px]">
        <n-virtual-list :item-size="106" :items="applicationList" class="!h-[500px] !pr-[14px]">
          <template #default="{ item }">
            <div
              :key="item.agentId"
              class="hover:!border-theme-color mb-[18px] box-border flex h-[88px] cursor-pointer select-none items-center rounded-[10px] border-[1px] border-solid border-[#ccc] px-[21px] transition"
              @click="handleNavigateToAppSetting(item.agentId)"
            >
              <img class="h-[46px] w-[46px] rounded-[6px] object-cover" :src="item.agentAvatar" alt="app-cover" />

              <div class="flex h-[46px] flex-1 flex-col justify-between overflow-hidden pl-[10px] pr-[20px]">
                <div class="text-[14px]">
                  <n-ellipsis :tooltip="{ 'content-style': 'max-width: 600px;' }">
                    {{ item.agentTitle || '-' }}
                  </n-ellipsis>
                </div>
                <div class="text-[12px]">
                  <n-ellipsis :tooltip="{ 'content-style': 'max-width: 600px;' }">
                    {{ item.agentDesc || '-' }}
                  </n-ellipsis>
                </div>
              </div>

              <n-button
                type="primary"
                :loading="currentApplicationPluginOperationLoading === item.agentId"
                :disabled="item.unitIds.includes(currentSelectPluginId)"
                @click.stop="handleAppAddPlugin(item.agentId)"
              >
                {{ t('common_module.add') }}
              </n-button>
            </div>
          </template>
        </n-virtual-list>
      </div>
      <div v-show="getApplicationListLoading" class="flex-center mt-[22px] flex h-[500px]">
        <n-spin size="large" />
      </div>
    </div>
  </n-modal>
</template>
