<script lang="ts" setup>
import type { MenuItem } from '#/components/zq-form/zq-menu-selector/types';

import { computed, ref, watch } from 'vue';

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

import {
  ElButton,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElMessage,
  ElScrollbar,
} from 'element-plus';

import { publishAgentToMenuApi } from '#/api/ai-platform/ai-platform';
import { ZqIconPicker } from '#/components/zq-form/zq-icon-picker';
import { ZqMenuSelector } from '#/components/zq-form/zq-menu-selector';
import { useAppContextStore } from '#/store/app-context';

interface Props {
  modelValue: boolean;
  agentId: string;
  agentName: string;
  agentCode?: string;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  published: [];
  'update:modelValue': [value: boolean];
}>();

const appContextStore = useAppContextStore();

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val),
});

const loading = ref(false);

// 发布表单
const publishForm = ref({
  menu_name: '',
  menu_parent_id: undefined as string | undefined,
  menu_icon: 'lucide:bot',
  menu_order: 0,
});

// 监听弹窗打开
watch(
  () => props.modelValue,
  (visible) => {
    if (visible) {
      // 重置表单，菜单名称默认为智能体名称
      publishForm.value = {
        menu_name: props.agentName,
        menu_parent_id: undefined,
        menu_icon: 'lucide:bot',
        menu_order: 0,
      };
    }
  },
);

// 菜单选择回调
function handleMenuChange(menu: MenuItem | MenuItem[] | null) {
  publishForm.value.menu_parent_id =
    menu && !Array.isArray(menu) ? menu.id : undefined;
}

async function handlePublish() {
  if (!publishForm.value.menu_name) {
    ElMessage.warning($t('ui.placeholder.input'));
    return;
  }

  loading.value = true;
  try {
    await publishAgentToMenuApi(props.agentId, {
      menu_name: publishForm.value.menu_name,
      menu_parent_id: publishForm.value.menu_parent_id,
      menu_icon: publishForm.value.menu_icon,
      menu_order: publishForm.value.menu_order,
    });
    ElMessage.success($t('common.operationSuccess'));
    emit('published');
    dialogVisible.value = false;
  } catch (error: any) {
    ElMessage.error(error?.message || $t('common.operationFailed'));
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <ElDialog
    v-model="dialogVisible"
    :title="$t('ai-platform.agent.publishToMenu')"
    width="500px"
    destroy-on-close
    align-center
    append-to-body
  >
    <ElScrollbar max-height="60vh">
      <div class="pr-4">
        <ElForm :model="publishForm" label-width="100px">
          <!-- 菜单配置 -->
          <div class="mb-4 font-medium">
            {{ $t('ai-platform.agent.publishDialog.menuConfig') }}
          </div>

          <ElFormItem
            :label="$t('ai-platform.agent.publishDialog.menuName')"
            required
          >
            <ElInput
              v-model="publishForm.menu_name"
              :placeholder="$t('ai-platform.agent.publishDialog.menuNamePlaceholder')"
            />
          </ElFormItem>

          <ElFormItem :label="$t('ai-platform.agent.publishDialog.parentMenu')">
            <ZqMenuSelector
              :model-value="publishForm.menu_parent_id || null"
              mode="dialog"
              :placeholder="
                $t('ai-platform.agent.publishDialog.parentMenuPlaceholder')
              "
              :application-id="appContextStore.currentApp?.id"
              @change="handleMenuChange"
            />
          </ElFormItem>

          <ElFormItem :label="$t('ai-platform.agent.publishDialog.menuIcon')">
            <ZqIconPicker
              v-model="publishForm.menu_icon"
              prefix="lucide"
              :auto-fetch-api="false"
              class="w-full"
            />
          </ElFormItem>

          <ElFormItem :label="$t('common.sort')">
            <ElInputNumber
              v-model="publishForm.menu_order"
              :min="0"
              :max="999"
              class="w-full"
            />
          </ElFormItem>

          <!-- 路由信息 -->
          <template v-if="agentCode">
            <div class="mb-4 mt-6 font-medium">
              {{ $t('ai-platform.agent.publishDialog.routeInfo') }}
            </div>

            <ElFormItem :label="$t('ai-platform.agent.publishDialog.accessPath')">
              <ElInput
                :model-value="`/agent-chat/${agentCode}`"
                disabled
                class="text-muted-foreground"
              />
            </ElFormItem>
          </template>
        </ElForm>
      </div>
    </ElScrollbar>

    <template #footer>
      <ElButton @click="dialogVisible = false">
        {{ $t('common.cancel') }}
      </ElButton>
      <ElButton type="primary" :loading="loading" @click="handlePublish">
        {{ $t('common.confirm') }}
      </ElButton>
    </template>
  </ElDialog>
</template>

<style>
/* 确保 IconPicker 的弹出层在 Dialog 之上 */
.z-popup {
  z-index: 2100 !important;
}
</style>
