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

/**
 * 对话历史列表组件
 * 显示智能体的历史对话列表，支持选择、删除、新建对话
 */
import { computed, onMounted, ref, watch } from 'vue';

import { Plus, Trash2 } from '@vben/icons';
import { $t } from '@vben/locales';

import {
  ElButton,
  ElEmpty,
  ElMessage,
  ElMessageBox,
  ElScrollbar,
  ElSkeleton,
  ElSkeletonItem,
} from 'element-plus';

import {
  createAgentConversationApi,
  deleteAgentConversationApi,
  getAgentConversationDetailApi,
  getAgentConversationsApi,
} from '#/api/ai-platform/ai-platform';
import { formatRelativeTime } from '#/utils/time';

// Props
const props = defineProps<{
  /** Agent ID */
  agentId: string;
  /** 当前选中的对话 ID */
  currentConversationId?: null | string;
  /** 是否显示新建按钮 */
  showNewButton?: boolean;
}>();

// Emits
const emit = defineEmits<{
  (e: 'select', conversationId: null | string): void;
  (e: 'new'): void;
}>();

// 状态
const loading = ref(false);
const conversations = ref<AgentConversation[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = 20;

// 加载对话列表
async function loadConversations(reset = false) {
  if (!props.agentId) return;

  if (reset) {
    page.value = 1;
    conversations.value = [];
  }

  loading.value = true;
  try {
    const res = await getAgentConversationsApi(props.agentId, {
      page: page.value,
      pageSize,
    });
    conversations.value = reset
      ? res.items
      : [...conversations.value, ...res.items];
    total.value = res.total;
  } catch (error: any) {
    console.error('加载对话列表失败:', error);
    ElMessage.error(
      error?.message || $t('ai-platform.conversation.loadFailed'),
    );
  } finally {
    loading.value = false;
  }
}

// 加载更多
function loadMore() {
  if (conversations.value.length < total.value && !loading.value) {
    page.value++;
    loadConversations();
  }
}

// 选择对话
function selectConversation(conversationId: string) {
  emit('select', conversationId);
}

// 新建对话
async function newConversation() {
  if (!props.agentId) return;

  try {
    loading.value = true;
    // 调用API创建新对话，默认标题为"新建对话"
    const newConv = await createAgentConversationApi(props.agentId, {
      title: '新建对话',
    });

    // 直接在顶部添加新对话，不重新加载整个列表
    conversations.value.unshift(newConv);
    total.value += 1;

    // 选中新创建的对话
    emit('select', newConv.id);
    emit('new');

    ElMessage.success('创建成功');
  } catch (error: any) {
    console.error('创建对话失败:', error);
    ElMessage.error(error?.message || '创建对话失败');
  } finally {
    loading.value = false;
  }
}

// 删除对话
async function deleteConversation(conversationId: string) {
  try {
    await ElMessageBox.confirm(
      $t('ai-platform.conversation.deleteConfirm'),
      $t('common.warning'),
      {
        confirmButtonText: $t('common.confirm'),
        cancelButtonText: $t('common.cancel'),
        type: 'warning',
      },
    );

    await deleteAgentConversationApi(conversationId);
    ElMessage.success($t('ai-platform.conversation.deleteSuccess'));

    // 从列表中移除
    conversations.value = conversations.value.filter(
      (c) => c.id !== conversationId,
    );
    total.value--;

    // 如果删除的是当前选中的对话，触发新建对话
    if (props.currentConversationId === conversationId) {
      emit('select', null);
      emit('new');
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除对话失败:', error);
      ElMessage.error(
        error?.message || $t('ai-platform.conversation.deleteFailed'),
      );
    }
  }
}

// 更新对话标题（无感更新，不刷新整个列表）
async function updateConversationTitle(conversationId: string) {
  try {
    // 获取对话详情
    const conversation = await getAgentConversationDetailApi(conversationId);

    // 在列表中找到对应的对话
    const index = conversations.value.findIndex((c) => c.id === conversationId);

    if (index === -1) {
      // 对话不存在（首次发送消息的情况），添加到列表顶部
      conversations.value.unshift(conversation);
      total.value += 1;
    } else {
      // 对话已存在，只更新字段
      const current = conversations.value[index];
      if (current) {
        current.title = conversation.title;
        current.message_count = conversation.message_count;
        if (conversation.sys_create_datetime) {
          current.sys_create_datetime = conversation.sys_create_datetime;
        }
      }
    }
  } catch (error: any) {
    console.error('更新对话标题失败:', error);
  }
}

// 是否有更多
const hasMore = computed(() => conversations.value.length < total.value);

// 监听 agentId 变化
watch(
  () => props.agentId,
  () => {
    loadConversations(true);
  },
);

// 初始化
onMounted(() => {
  loadConversations(true);
});

// 暴露方法
defineExpose({
  refresh: () => loadConversations(true),
  updateConversationTitle,
});
</script>

<template>
  <div class="flex h-full flex-col">
    <!-- 头部 -->
    <div class="border-border flex items-center justify-between px-4 pb-2 pt-4">
      <span class="text-foreground text-sm font-medium">
        {{ $t('ai-platform.conversation.history') }}
      </span>
      <ElButton
        v-if="showNewButton !== false"
        size="small"
        :icon="Plus"
        @click="newConversation"
      >
        <!-- {{ $t('ai-platform.conversation.new') }} -->
      </ElButton>
    </div>

    <!-- 列表 -->
    <ElScrollbar class="flex-1">
      <div class="p-2">
        <!-- 骨架屏 -->
        <div v-if="loading && conversations.length === 0" class="space-y-2">
          <div v-for="i in 5" :key="i" class="rounded-lg px-3 py-2">
            <ElSkeleton animated>
              <template #template>
                <ElSkeletonItem
                  variant="text"
                  style="width: 100%; height: 32px"
                />
              </template>
            </ElSkeleton>
          </div>
        </div>

        <!-- 空状态 -->
        <ElEmpty
          v-else-if="!loading && conversations.length === 0"
          :description="$t('ai-platform.conversation.empty')"
          :image-size="60"
        />

        <!-- 对话列表 -->
        <div v-else class="space-y-1">
          <div
            v-for="conv in conversations"
            :key="conv.id"
            class="hover:bg-accent group relative cursor-pointer rounded-lg px-3 py-2 transition-colors"
            :class="{
              'bg-accent': currentConversationId === conv.id,
            }"
            @click="selectConversation(conv.id)"
          >
            <!-- 标题 -->
            <div class="text-foreground truncate text-sm font-medium">
              {{ conv.title || $t('ai-platform.conversation.untitled') }}
            </div>
            <!-- 时间 -->
            <div class="text-muted-foreground mt-1 text-xs">
              {{
                formatRelativeTime(conv.sys_create_datetime || conv.created_at)
              }}
            </div>

            <!-- 删除按钮 -->
            <ElButton
              class="absolute right-2 top-1/2 -translate-y-1/2 opacity-0 transition-opacity group-hover:opacity-100"
              type="danger"
              link
              size="small"
              :icon="Trash2"
              @click.stop="deleteConversation(conv.id)"
            />
          </div>

          <!-- 加载更多 -->
          <div
            v-if="hasMore"
            class="text-muted-foreground hover:text-primary cursor-pointer py-2 text-center text-xs"
            @click="loadMore"
          >
            {{ loading ? $t('common.loading') : $t('common.loadMore') }}
          </div>
        </div>
      </div>
    </ElScrollbar>
  </div>
</template>
