<script setup lang="ts">
import type { PluginToolListRouteState } from './plugin-route-state';

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 {
  buildListRouteFullPath,
  watchListRouteState,
} from '#/composables/useListRouteState';
import { navigateBackToList } from '#/router/list-return-context';
import PluginToolTable from '#/views/ai/plugin/PluginToolTable.vue';

import {
  mergePluginToolListRouteQuery,
  parsePluginToolListRouteState,
  pluginToolListRouteSchema,
} from './plugin-route-state';

const route = useRoute();
const router = useRouter();
const initialToolListState = parsePluginToolListRouteState(route.query);

const pluginId = ref<string>((route.query.id as string) || '');
const pluginInfo = ref<any>({});
const pluginToolRef = ref();
const toolSearchKeyword = ref(initialToolListState.keyword.trim());
const currentToolPageNumber = ref(initialToolListState.pageNumber);
const currentToolPageSize = ref(initialToolListState.pageSize);
watchListRouteState(route, pluginToolListRouteSchema, (state) => {
  const nextPluginId = String(route.query.id || '');
  const pluginChanged = nextPluginId !== pluginId.value;
  pluginId.value = nextPluginId;
  toolSearchKeyword.value = state.keyword.trim();
  currentToolPageNumber.value = state.pageNumber;
  currentToolPageSize.value = state.pageSize;
  const restored = pluginToolRef.value?.restoreState?.(state);
  if (pluginChanged) {
    pluginInfo.value = {};
    if (!restored) pluginToolRef.value?.reload?.();
    void loadPluginInfo();
  }
});

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 currentToolListState(): PluginToolListRouteState {
  return {
    keyword: toolSearchKeyword.value,
    pageNumber: currentToolPageNumber.value,
    pageSize: currentToolPageSize.value,
  };
}

function currentToolListFullPath() {
  return buildListRouteFullPath(
    router,
    route.query,
    currentToolListState(),
    pluginToolListRouteSchema,
  );
}

function syncToolListRouteState() {
  const target = {
    path: '/ai/plugin/tools',
    query: mergePluginToolListRouteQuery(route.query, currentToolListState()),
  };
  if (router.resolve(target).fullPath !== route.fullPath) {
    void router.replace(target);
  }
}

function handleToolPageStateChange(state: {
  pageNumber: number;
  pageSize: number;
}) {
  currentToolPageNumber.value = state.pageNumber;
  currentToolPageSize.value = state.pageSize;
  syncToolListRouteState();
}

function handleSearch(params: string) {
  toolSearchKeyword.value = params.trim();
  pluginToolRef.value.handleSearch(toolSearchKeyword.value);
}

function handleButtonClick(event: any) {
  switch (event.key) {
    case 'back': {
      void navigateBackToList(
        router,
        route.query,
        ['/ai/plugin'],
        '/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"
      :initial-value="toolSearchKeyword"
      @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"
        :initial-keyword="initialToolListState.keyword"
        :initial-page-number="initialToolListState.pageNumber"
        :initial-page-size="initialToolListState.pageSize"
        :return-to="currentToolListFullPath()"
        @state-change="handleToolPageStateChange"
      />
    </div>
  </div>
</template>
