<script setup lang="ts">
import type { ChatTimeTimelineItem } from '@easyflow/types';

import { Close } from '@element-plus/icons-vue';
import { ElButton, ElEmpty, ElIcon, ElScrollbar } from 'element-plus';

import ChatTimeMessageContent from '#/components/chat/ChatTimeMessageContent.vue';
import ChatMessageActionBar from '#/components/chat-workspace/ChatMessageActionBar.vue';

interface ChatHistoryDetailDrawerProps {
  visible?: boolean;
  loading?: boolean;
  session?: any;
  messages?: ChatTimeTimelineItem[];
  hasMore?: boolean;
  onLoadMore?: (() => Promise<void> | void) | undefined;
  switchingRoundIds?: string[];
}

const props = withDefaults(defineProps<ChatHistoryDetailDrawerProps>(), {
  visible: false,
  loading: false,
  session: undefined,
  messages: () => [],
  hasMore: false,
  onLoadMore: undefined,
  switchingRoundIds: () => [],
});

const emit = defineEmits<{
  close: [];
  selectVariant: [
    payload: {
      direction: 'next' | 'previous';
      item: ChatTimeTimelineItem;
    },
  ];
}>();

function formatTime(value?: number | string) {
  if (!value) {
    return '-';
  }
  const time = new Date(value);
  if (Number.isNaN(time.getTime())) {
    return value;
  }
  const year = time.getFullYear();
  const month = String(time.getMonth() + 1).padStart(2, '0');
  const day = String(time.getDate()).padStart(2, '0');
  const hour = String(time.getHours()).padStart(2, '0');
  const minute = String(time.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}`;
}

function resolveSenderName(item: any) {
  if (item?.senderName) {
    return item.senderName;
  }
  if (item?.role === 'tool') {
    return '工具调用';
  }
  return item?.role === 'assistant' ? '智能体' : '聊天用户';
}

async function handleLoadMore() {
  await props.onLoadMore?.();
}

function shouldShowVariantNavigator(item: ChatTimeTimelineItem) {
  return (
    item.role === 'assistant' &&
    isFinalAssistantInRound(item) &&
    Number(item.variantCount || 0) > 1 &&
    Boolean(item.roundId)
  );
}

function canSwitchVariant(
  item: ChatTimeTimelineItem,
  direction: 'next' | 'previous',
) {
  if (
    item.role !== 'assistant' ||
    !isFinalAssistantInRound(item) ||
    !item.switchable ||
    isVariantSwitching(item)
  ) {
    return false;
  }
  const current = Number(item.variantIndex || item.selectedVariantIndex || 1);
  const total = Number(item.variantCount || 1);
  if (direction === 'previous') {
    return current > 1;
  }
  return current < total;
}

function isVariantSwitching(item: ChatTimeTimelineItem) {
  return Boolean(
    item.roundId && props.switchingRoundIds.includes(String(item.roundId)),
  );
}

function isFinalAssistantInRound(item: ChatTimeTimelineItem) {
  if (item.role !== 'assistant') {
    return false;
  }
  if (!item.roundId) {
    return true;
  }
  for (let index = props.messages.length - 1; index >= 0; index -= 1) {
    const candidate = props.messages[index];
    if (
      candidate?.role === 'assistant' &&
      candidate.roundId === item.roundId &&
      String(candidate.variantIndex || '') === String(item.variantIndex || '')
    ) {
      return candidate.id === item.id;
    }
  }
  return true;
}

function canCopyMessage(item: ChatTimeTimelineItem) {
  return item.role !== 'tool' && Boolean(String(item.content || '').trim());
}
</script>

<template>
  <div
    v-loading="loading"
    class="chat-history-detail"
    :class="{ 'is-visible': visible }"
  >
    <div class="chat-history-detail__summary">
      <div class="chat-history-detail__summary-main">
        <div class="chat-history-detail__title-row">
          <h2 class="chat-history-detail__title">
            {{ session?.title || '未命名会话' }}
          </h2>
          <span class="chat-history-detail__assistant-tag">
            {{ session?.assistantName || '智能体' }}
          </span>
        </div>
        <div class="chat-history-detail__meta-row">
          <span class="chat-history-detail__meta-inline">
            <span class="chat-history-detail__meta-label">聊天用户</span>
            <span class="chat-history-detail__meta-value">
              {{ session?.userAccount || '-' }}
            </span>
          </span>
          <span class="chat-history-detail__meta-divider"></span>
          <span class="chat-history-detail__meta-inline">
            <span class="chat-history-detail__meta-label">最近活跃</span>
            <span class="chat-history-detail__meta-value">
              {{ formatTime(session?.lastMessageAt || session?.accessAt) }}
            </span>
          </span>
          <span class="chat-history-detail__meta-divider"></span>
          <span class="chat-history-detail__meta-inline">
            <span class="chat-history-detail__meta-label">消息数</span>
            <span class="chat-history-detail__meta-value">
              {{ session?.messageCount ?? messages.length ?? 0 }}
            </span>
          </span>
        </div>
      </div>

      <button
        type="button"
        class="chat-history-detail__close"
        aria-label="关闭聊天详情"
        @click="emit('close')"
      >
        <ElIcon size="18">
          <Close />
        </ElIcon>
      </button>
    </div>

    <div class="chat-history-detail__stream">
      <div class="chat-history-detail__stream-toolbar">
        <ElButton v-if="hasMore" text type="primary" @click="handleLoadMore">
          加载更早消息
        </ElButton>
      </div>

      <ElScrollbar class="chat-history-detail__scrollbar">
        <div
          v-if="messages.length > 0"
          class="chat-history-detail__message-list"
        >
          <article
            v-for="item in messages"
            :key="item.id"
            class="chat-history-detail__message"
            :class="`is-${item.role}`"
          >
            <div
              class="chat-history-detail__message-meta"
              :class="`is-${item.role}`"
            >
              <span class="chat-history-detail__message-author">
                {{ resolveSenderName(item) }}
              </span>
              <span class="chat-history-detail__message-time">
                {{ formatTime(item.created) }}
              </span>
            </div>

            <div
              class="chat-history-detail__message-bubble"
              :class="`is-${item.role}`"
            >
              <ChatTimeMessageContent :item="item" readonly-thinking />
            </div>

            <ChatMessageActionBar
              :align="item.role === 'user' ? 'end' : 'start'"
              :allow-copy="canCopyMessage(item)"
              :copy-text="String(item.content || '').trim()"
              :show-variant-navigator="shouldShowVariantNavigator(item)"
              :disabled-variant-next="!canSwitchVariant(item, 'next')"
              :disabled-variant-previous="!canSwitchVariant(item, 'previous')"
              :variant-loading="isVariantSwitching(item)"
              :variant-current="
                Number(item.variantIndex || item.selectedVariantIndex || 1)
              "
              :variant-total="Number(item.variantCount || 1)"
              @select-next-variant="
                emit('selectVariant', { direction: 'next', item })
              "
              @select-previous-variant="
                emit('selectVariant', { direction: 'previous', item })
              "
            />
          </article>
        </div>

        <ElEmpty v-else description="暂无聊天消息" />
      </ElScrollbar>
    </div>
  </div>
</template>

<style scoped>
.chat-history-detail {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
  background:
    radial-gradient(
      circle at top right,
      hsl(var(--nav-ambient) / 10%),
      transparent 26%
    ),
    linear-gradient(
      180deg,
      hsl(var(--glass-border) / 18%) 0%,
      hsl(var(--glass-tint) / 34%) 10%,
      hsl(var(--surface-panel) / 88%) 28%,
      hsl(var(--surface-panel) / 96%) 100%
    );
}

.chat-history-detail__summary {
  display: flex;
  gap: 16px;
  align-items: flex-start;
  justify-content: space-between;
  padding: 20px 24px 12px;
  border-bottom: 1px solid hsl(var(--divider-faint) / 16%);
}

.chat-history-detail__summary-main {
  flex: 1;
  min-width: 0;
}

.chat-history-detail__title-row {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

.chat-history-detail__title {
  min-width: 0;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: hsl(var(--text-strong));
}

.chat-history-detail__assistant-tag {
  display: inline-flex;
  align-items: center;
  min-height: 26px;
  padding: 0 10px;
  font-size: 12px;
  font-weight: 600;
  color: hsl(var(--nav-item-active-foreground));
  background: hsl(var(--glass-tint) / 54%);
  border: 1px solid hsl(var(--glass-border) / 38%);
  border-radius: 999px;
}

.chat-history-detail__meta-row {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
  margin-top: 10px;
}

.chat-history-detail__meta-label {
  font-size: 11px;
  color: hsl(var(--text-muted));
}

.chat-history-detail__meta-value {
  min-width: 0;
  font-size: 12px;
  font-weight: 600;
  color: hsl(var(--text-strong));
  word-break: break-all;
}

.chat-history-detail__meta-inline {
  display: inline-flex;
  gap: 6px;
  align-items: center;
  min-width: 0;
}

.chat-history-detail__meta-divider {
  display: inline-flex;
  width: 1px;
  height: 12px;
  background: hsl(var(--divider-faint) / 42%);
}

.chat-history-detail__close {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  color: hsl(var(--text-muted));
  background: hsl(var(--glass-tint) / 46%);
  border: 1px solid hsl(var(--divider-faint) / 24%);
  border-radius: 999px;
  transition:
    transform 0.18s ease,
    background-color 0.18s ease,
    color 0.18s ease;
}

.chat-history-detail__close:hover {
  color: hsl(var(--text-strong));
  background: hsl(var(--surface-contrast-soft) / 92%);
  transform: translateY(-1px);
}

.chat-history-detail__stream {
  display: flex;
  flex: 1;
  flex-direction: column;
  min-height: 0;
  padding: 14px 24px 20px;
}

.chat-history-detail__stream-toolbar {
  display: flex;
  justify-content: center;
  padding-bottom: 12px;
}

.chat-history-detail__scrollbar {
  flex: 1;
  min-height: 0;
}

.chat-history-detail__message-list {
  display: flex;
  flex-direction: column;
  gap: 18px;
}

.chat-history-detail__message {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.chat-history-detail__message.is-user {
  align-items: flex-end;
}

.chat-history-detail__message.is-assistant {
  align-items: flex-start;
}

.chat-history-detail__message-meta {
  display: inline-flex;
  gap: 10px;
  align-items: center;
  max-width: 88%;
  font-size: 11px;
  color: hsl(var(--text-muted));
}

.chat-history-detail__message-meta.is-user {
  justify-content: flex-end;
}

.chat-history-detail__message-author {
  font-weight: 600;
  color: hsl(var(--text-strong));
}

.chat-history-detail__message-bubble {
  width: min(88%, 760px);
  padding: 14px 16px;
  font-size: 14px;
  line-height: 1.72;
  border: 1px solid hsl(var(--divider-faint) / 34%);
  border-radius: 22px;
  backdrop-filter: blur(10px);
}

.chat-history-detail__message-bubble.is-assistant {
  background: hsl(var(--glass-tint) / 88%);
  box-shadow:
    inset 0 1px 0 hsl(var(--glass-border) / 48%),
    0 12px 26px -24px hsl(var(--foreground) / 18%);
}

.chat-history-detail__message-bubble.is-user {
  background: linear-gradient(
    180deg,
    hsl(var(--primary) / 14%) 0%,
    hsl(var(--surface-panel) / 96%) 100%
  );
  box-shadow:
    inset 0 1px 0 hsl(var(--glass-border) / 42%),
    0 16px 30px -26px hsl(var(--primary) / 24%);
}

.chat-history-detail__message-chains {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 4px;
}

.chat-history-detail__thinking {
  width: 100%;
}

.chat-history-detail__tool-panel {
  overflow: hidden;
  background: hsl(var(--surface-panel) / 68%);
  border: 1px solid hsl(var(--divider-faint) / 24%);
  border-radius: 14px;
  box-shadow: inset 0 1px 0 hsl(var(--glass-border) / 18%);
}

.chat-history-detail__tool-title {
  display: flex;
  gap: 8px;
  align-items: center;
  min-width: 0;
  padding-left: 6px;
}

.chat-history-detail__tool-name {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chat-history-detail__tool-status {
  display: inline-flex;
  gap: 6px;
  align-items: center;
  padding: 4px 8px;
  font-size: 12px;
  color: hsl(var(--text-muted));
  background: hsl(var(--surface-contrast-soft) / 92%);
  border-radius: 999px;
}

.chat-history-detail__markdown {
  min-width: 0;
}

.chat-history-detail__tool-panel :deep(.el-collapse-item__wrap) {
  background: transparent;
}

.chat-history-detail__tool-panel :deep(.el-collapse-item__header) {
  min-height: 44px;
  padding-right: 14px;
  background: transparent;
  border-bottom-color: hsl(var(--divider-faint) / 16%);
}

.chat-history-detail__message-bubble :deep(.el-collapse-item__content) {
  padding-bottom: 0;
}

@media (max-width: 900px) {
  .chat-history-detail__summary {
    padding: 18px 18px 12px;
  }

  .chat-history-detail__stream {
    padding: 12px 18px 18px;
  }

  .chat-history-detail__meta-row {
    gap: 6px;
  }

  .chat-history-detail__meta-divider {
    display: none;
  }

  .chat-history-detail__meta-inline {
    width: 100%;
  }

  .chat-history-detail__message-bubble,
  .chat-history-detail__message-meta {
    width: 100%;
    max-width: 100%;
  }
}
</style>
