<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { Plus, RightOne } from '@icon-park/vue-next'
import { useI18n } from 'vue-i18n'
import AddAgentPluginModal from './add-agent-plugin-modal.vue'
import { PersonalAppConfigState } from '@/store/types/personal-app-config'
import { fetchPluginCategoryDetailInfoList } from '@/apis/plugin-center'

interface PluginItemInterface {
  pluginId: string
  title: string
  points: number
  description: string
  icon: string
}

const { t } = useI18n()

const unitIds = defineModel<PersonalAppConfigState['unitIds']>('unitIds', { required: true })

const pluginExpandedNames = ref<string[]>([])
const selectedPluginList = ref<PluginItemInterface[]>([])
const isShowAddAgentPluginModal = ref(false)
const hoverUnitId = ref('')

const defaultPluginIconUrl = 'https://gsst-poe-sit.gz.bcebos.com/data/20250115/1736924150557.png'

const isHoverPluginItem = computed(() => (pluginId: string) => {
  return hoverUnitId.value === pluginId
})

watch(
  () => unitIds.value,
  async (newUnitIds) => {
    if (newUnitIds.length > 0) {
      await handleGetPluginList()
      pluginExpandedNames.value = ['plugin']
    }
  },
  { once: true, immediate: true },
)

function handleUpdatePluginExpandedNames(expandedNames: string[]) {
  pluginExpandedNames.value = expandedNames
}

function handleShowAddAgentPluginModel() {
  isShowAddAgentPluginModal.value = true
}

async function handleGetPluginList() {
  const payload = {
    classification: '',
    pluginIds: unitIds.value,
  }

  const res = await fetchPluginCategoryDetailInfoList<{ pluginInfos: PluginItemInterface[] }[]>(payload)

  if (res.code === 0) {
    selectedPluginList.value = []

    res.data.forEach((pluginClassificationItem) => {
      pluginClassificationItem.pluginInfos.forEach((pluginItem) => {
        selectedPluginList.value.push(pluginItem)
      })
    })
  }
}

function handleMouseoverPluginItem(pluginId: string) {
  hoverUnitId.value = pluginId
}

function handleMouseleavePluginItem() {
  hoverUnitId.value = ''
}

function handleDeleteUnitId(pluginId: string) {
  unitIds.value = unitIds.value.filter((id) => id !== pluginId)
  selectedPluginList.value = selectedPluginList.value.filter((pluginItem) => pluginItem.pluginId !== pluginId)
}

async function handleCloseAgentPluginModal() {
  if (!unitIds.value.length) {
    selectedPluginList.value = []
    return
  }

  await handleGetPluginList()
  pluginExpandedNames.value = ['plugin']
}
</script>

<template>
  <section class="border-b border-[#e8e9eb] px-5">
    <div class="pt-4">
      <h2 class="mb-3 text-[#84868c]">
        {{ t('personal_space_module.agent_module.agent_setting_module.agent_config_module.plugin') }}
      </h2>

      <NCollapse
        :expanded-names="pluginExpandedNames"
        :trigger-areas="['main', 'arrow']"
        @update:expanded-names="handleUpdatePluginExpandedNames"
      >
        <template #arrow>
          <RightOne theme="filled" size="17" fill="#333" :stroke-width="3" />
        </template>

        <NCollapseItem
          :title="t('personal_space_module.agent_module.agent_setting_module.agent_config_module.plugin')"
          name="plugin"
          class="my-[13px]!"
        >
          <template #header-extra>
            <NTooltip trigger="hover">
              <template #trigger>
                <Plus
                  theme="outline"
                  size="22"
                  :stroke-width="3"
                  class="text-theme-color cursor-pointer"
                  @click="handleShowAddAgentPluginModel"
                />
              </template>
              {{ t('personal_space_module.agent_module.agent_setting_module.agent_config_module.add_plugin') }}
            </NTooltip>
          </template>

          <ul v-show="selectedPluginList.length" class="flex flex-col gap-2">
            <li
              v-for="pluginItem in selectedPluginList"
              :key="pluginItem.pluginId"
              class="flex h-[66px] items-center gap-[12px] overflow-hidden rounded-[10px] border border-[#f2f5f9] px-4 hover:bg-[#f2f5f9]"
              @mouseover="handleMouseoverPluginItem(pluginItem.pluginId)"
              @mouseleave="handleMouseleavePluginItem"
            >
              <div
                class="h-[36px] w-[36px] flex-shrink-0 bg-contain bg-center bg-no-repeat"
                :style="
                  pluginItem.icon
                    ? { backgroundImage: `url(${pluginItem.icon})` }
                    : { backgroundImage: `url(${defaultPluginIconUrl})` }
                "
              />

              <div class="flex h-full flex-1 flex-col justify-center overflow-hidden">
                <div class="w-full text-[14px]">
                  <n-ellipsis class="text-font-color w-full" :tooltip="{ 'content-style': 'max-width: 600px;' }">
                    {{ pluginItem.title }}
                  </n-ellipsis>
                </div>

                <div class="w-full text-[12px]">
                  <n-ellipsis class="text-gray-font-color w-full" :tooltip="{ 'content-style': 'max-width: 600px;' }">
                    {{ pluginItem.description }}
                  </n-ellipsis>
                </div>
              </div>

              <n-tooltip placement="top">
                <template #trigger>
                  <div
                    v-show="isHoverPluginItem(pluginItem.pluginId)"
                    class="flex cursor-pointer items-center justify-center"
                    @click="handleDeleteUnitId(pluginItem.pluginId)"
                  >
                    <i class="hover:text-error-font-color text-font-color iconfont icon-reduce outline-none" />
                  </div>
                </template>
                <span>{{ t('common_module.remove') }}</span>
              </n-tooltip>
            </li>
          </ul>

          <div v-show="selectedPluginList.length === 0">
            <span class="text-xs text-[#84868c]">
              {{ t('personal_space_module.agent_module.agent_setting_module.agent_config_module.plugin_desc') }}
            </span>
          </div>
        </NCollapseItem>
      </NCollapse>
    </div>
  </section>

  <AddAgentPluginModal
    v-model:is-show-modal="isShowAddAgentPluginModal"
    v-model:plugin-id-list="unitIds"
    :modal-title="t('personal_space_module.agent_module.agent_setting_module.agent_config_module.add_plugin')"
    @close="handleCloseAgentPluginModal"
  />
</template>
