<script setup lang="ts">
import { computed, markRaw, onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import { $t } from '@easyflow/locales';

import { Back, Plus } from '@element-plus/icons-vue';

import { api } from '#/api/request';
import HeaderSearch from '#/components/headerSearch/HeaderSearch.vue';
import PluginToolTable from '#/views/ai/plugin/PluginToolTable.vue';

const route = useRoute();
const router = useRouter();

const pluginId = ref<string>((route.query.id as string) || '');
const pluginInfo = ref<any>({});
const pluginToolRef = ref();

const headerButtons = computed<any[]>(() => {
  const buttons: any[] = [
    {
      key: 'back',
      text: $t('button.back'),
      icon: markRaw(Back),
      data: { action: 'back' },
    },
  ];
  if (Number(pluginInfo.value?.type || 1) !== 2) {
    buttons.push({
      key: 'createTool',
      text: $t('pluginItem.createPluginTool'),
      icon: markRaw(Plus),
      type: 'primary',
      data: { action: 'createTool' },
    });
  }
  return buttons;
});

onMounted(() => {
  loadPluginInfo();
});

async function loadPluginInfo() {
  if (!pluginId.value) {
    return;
  }
  const res = await api.get(`/api/v1/plugin/detail?id=${pluginId.value}`);
  if (res.errorCode === 0) {
    pluginInfo.value = res.data || {};
  }
}

function handleSearch(params: any) {
  pluginToolRef.value.handleSearch(params);
}

function handleButtonClick(event: any) {
  switch (event.key) {
    case 'back': {
      router.push({ path: '/ai/plugin' });
      break;
    }
    case 'createTool': {
      pluginToolRef.value.openPluginToolModal({});
      break;
    }
  }
}
</script>

<template>
  <div class="flex h-full flex-col gap-6 p-6">
    <HeaderSearch
      :buttons="headerButtons"
      @search="handleSearch"
      @button-click="handleButtonClick"
    />

    <div class="bg-background border-border flex-1 rounded-lg border p-5">
      <PluginToolTable
        ref="pluginToolRef"
        :plugin-id="pluginId"
        :plugin-type="pluginInfo.type"
      />
    </div>
  </div>
</template>
