<script lang="ts" setup>
import type { Agent } from '#/api/ai-platform/ai-platform';

import { computed, defineAsyncComponent, onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';

import { Page } from '@vben/common-ui';
import { PanelLeft, PanelRight } from '@vben/icons';
import { $t } from '@vben/locales';

import { ElButton, ElEmpty } from 'element-plus';

import { getAgentByCodeApi } from '#/api/ai-platform/ai-platform';

const AiChatPanel = defineAsyncComponent(() =>
  import('#/components/ai-chat-panel/AiChatPanel.vue'),
);
const ConversationList = defineAsyncComponent(() =>
  import('#/components/ai-chat-panel/ConversationList.vue'),
);

defineOptions({ name: 'AgentChat' });

const route = useRoute();

// 从路由获取 agentCode
const agentCode = computed((): string => {
  // 优先从 query 获取
  if (route.query.agentCode) {
    return route.query.agentCode as string;
  }

  // 其次从 params 获取
  if (route.params.code) {
    return route.params.code as string;
  }

  // 最后从路径中提取（路径格式：/agent-chat/xxx）
  const pathParts = route.path.split('/').filter(Boolean);
  const length = pathParts.length;
  if (length >= 2 && pathParts[length - 2] === 'agent-chat') {
    return pathParts[length - 1] || '';
  }

  return '';
});

// 状态
const loading = ref(true);
const agent = ref<Agent | null>(null);
const error = ref<null | string>(null);
const currentConversationId = ref<null | string>(null);
const showHistoryPanel = ref(false);
const conversationListRef = ref();

// 加载智能体
async function loadAgent() {
  if (!agentCode.value) {
    error.value = $t('ai-platform.agent.codeRequired');
    loading.value = false;
    return;
  }

  loading.value = true;
  error.value = null;

  try {
    agent.value = await getAgentByCodeApi(agentCode.value);
  } catch (error_: any) {
    error.value = error_?.message || $t('ai-platform.agent.loadFailed');
  } finally {
    loading.value = false;
  }
}

// 选择对话
function handleSelectConversation(conversationId: null | string) {
  currentConversationId.value = conversationId;
}

// 新建对话（现在由 ConversationList 组件处理）
function handleNewConversation() {
  // ConversationList 会自动创建对话并通过 @select 事件传递新对话ID
}

// 消息发送完成后更新对话标题（无感更新，不刷新整个列表）
function handleMessageComplete(conversationId: null | string) {
  if (conversationId) {
    conversationListRef.value?.updateConversationTitle(conversationId);
    // 注意：不设置 currentConversationId，避免触发历史消息加载导致 ChatBox 刷新
    // 对话已经在进行中，无需重新加载历史消息
  }
}

// 切换历史面板
function toggleHistoryPanel() {
  showHistoryPanel.value = !showHistoryPanel.value;
}

onMounted(() => {
  loadAgent();
});
</script>

<template>
  <Page auto-content-height>
    <div v-loading="loading" class="flex h-full">
      <!-- 错误 -->
      <template v-if="!loading && (error || !agent)">
        <div class="flex flex-1 items-center justify-center">
          <ElEmpty :description="error || $t('ai-platform.agent.notFound')" />
        </div>
      </template>

      <!-- 主内容 -->
      <template v-else-if="!loading && agent">
        <!-- 左侧历史记录面板 -->
        <div
          v-if="showHistoryPanel"
          class="bg-card mr-3 h-full w-64 flex-shrink-0 rounded-[8px]"
        >
          <ConversationList
            ref="conversationListRef"
            :agent-id="agent.id"
            :show-new-button="true"
            :current-conversation-id="currentConversationId"
            @select="handleSelectConversation"
            @new="handleNewConversation"
          />
        </div>

        <!-- 聊天面板 -->
        <div class="relative flex flex-1 flex-col overflow-hidden">
          <!-- 切换按钮 -->
          <ElButton
            class="absolute left-2 top-2 z-10"
            :icon="showHistoryPanel ? PanelLeft : PanelRight"
            link
            @click="toggleHistoryPanel"
          />

          <AiChatPanel
            :key="currentConversationId || 'new'"
            mode="agent-chat"
            layout="fullscreen"
            :agent="agent"
            :agent-id="agent.id"
            :conversation-id="currentConversationId"
            :enable-attachment="true"
            :enable-image="true"
            :show-clear-button="true"
            :show-header="false"
            class="flex-1"
            @message-complete="handleMessageComplete"
          />
        </div>
      </template>
    </div>
  </Page>
</template>
