<template>
  <div class="chat-sidebar">
    <div class="chat-sidebar__header">
      <a-button type="primary" block @click="handleCreate">
        <template #icon><PlusOutlined /></template>
        新建对话
      </a-button>
    </div>
    <div class="chat-sidebar__list">
      <a-empty v-if="conversations.length === 0" description="暂无对话" />
      <div
        v-for="conv in conversations"
        :key="conv.id"
        class="chat-sidebar__item"
        :class="{ 'chat-sidebar__item--active': conv.id === currentId }"
        @click="handleSelect(conv.id)"
      >
        <MessageOutlined class="chat-sidebar__item-icon" />
        <span class="chat-sidebar__item-title">{{ conv.title }}</span>
        <span class="chat-sidebar__item-time">{{ formatRelativeTime(conv.updated_at) }}</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Button as AButton, Empty as AEmpty } from 'ant-design-vue'
import { PlusOutlined, MessageOutlined } from '@ant-design/icons-vue'
import type { IConversation } from '@/api/types'

interface IProps {
  conversations: IConversation[]
  currentId: string | null
}

defineProps<IProps>()

const emit = defineEmits<{
  create: []
  select: [id: string]
}>()

function handleCreate(): void {
  emit('create')
}

function handleSelect(id: string): void {
  emit('select', id)
}

function formatRelativeTime(dateStr: string): string {
  const date = new Date(dateStr)
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffMin = Math.floor(diffMs / 60000)

  if (diffMin < 1) return '刚刚'
  if (diffMin < 60) return `${diffMin}分钟前`

  const diffHour = Math.floor(diffMin / 60)
  if (diffHour < 24) return `${diffHour}小时前`

  const diffDay = Math.floor(diffHour / 24)
  if (diffDay < 7) return `${diffDay}天前`

  return date.toLocaleDateString('zh-CN')
}
</script>

<style scoped>
.chat-sidebar {
  width: 280px;
  height: 100%;
  background: #ffffff;
  border-right: 1px solid #f0f0f0;
  display: flex;
  flex-direction: column;
}

.chat-sidebar__header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.chat-sidebar__list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.chat-sidebar__item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: background 0.2s;
}

.chat-sidebar__item:hover {
  background: #f5f5f5;
}

.chat-sidebar__item--active {
  background: #e6f4ff;
}

.chat-sidebar__item--active:hover {
  background: #e6f4ff;
}

.chat-sidebar__item-icon {
  color: #999999;
  font-size: 14px;
  flex-shrink: 0;
}

.chat-sidebar__item--active .chat-sidebar__item-icon {
  color: #1677ff;
}

.chat-sidebar__item-title {
  flex: 1;
  font-size: 14px;
  color: #333333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chat-sidebar__item-time {
  font-size: 12px;
  color: #999999;
  flex-shrink: 0;
}
</style>
