<template>
  <div class="list-view">
    <!-- Batch operations toolbar -->
    <div v-if="selectedRowKeys.length > 0" class="list-view__toolbar">
      <span class="list-view__toolbar-count">已选 {{ selectedRowKeys.length }} 项</span>
      <a-space>
        <a-popconfirm title="确认删除选中事件？" @confirm="batchDelete">
          <a-button size="small" danger>
            <template #icon><DeleteOutlined /></template>
            删除
          </a-button>
        </a-popconfirm>
        <a-select
          v-model:value="batchTypeId"
          size="small"
          placeholder="更改类型"
          allowClear
          style="width: 140px"
          @change="batchChangeType"
        >
          <a-select-option v-for="t in store.eventTypes" :key="t.id" :value="t.id">
            {{ t.name }}
          </a-select-option>
        </a-select>
        <!-- ponytail: IUpdateEventRequest has no tag_ids field; batch add-tag is UI-only until backend supports it. -->
        <a-input-search
          v-model:value="batchTagName"
          size="small"
          placeholder="添加标签"
          style="width: 140px"
          @search="batchAddTag"
        />
        <a-button size="small" @click="clearSelection">取消选择</a-button>
      </a-space>
    </div>

    <a-empty v-if="sortedEvents.length === 0" description="暂无日程" class="list-view__empty" />
    <a-table
      v-else
      :dataSource="sortedEvents"
      :columns="columns"
      rowKey="id"
      size="small"
      :pagination="{ pageSize: 50, showSizeChanger: false }"
      :customRow="customRow"
      :rowSelection="rowSelection"
      :scroll="{ y: 'calc(100% - 64px)' }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'start_time'">
          <span class="list-view__time">
            {{ formatDateTime(record.start_time) }}
            <span class="list-view__time-sep">→</span>
            {{ formatTime(record.end_time) }}
          </span>
        </template>
        <template v-else-if="column.key === 'title'">
          <span class="list-view__title" :class="{ 'list-view__title--invited': record.is_invited }">
            {{ record.title }}
            <a-tag v-if="record.is_invited" color="purple" size="small">受邀</a-tag>
          </span>
        </template>
        <template v-else-if="column.key === 'source'">
          <EventBadge :event="record" />
        </template>
        <template v-else-if="column.key === 'event_type_id'">
          <a-tag
            v-if="record.event_type_id"
            :color="getTypeColor(record.event_type_id)"
            size="small"
          >
            {{ getTypeName(record.event_type_id) }}
          </a-tag>
          <span v-else class="list-view__muted">—</span>
        </template>
        <template v-else-if="column.key === 'location'">
          <span v-if="record.location">{{ record.location }}</span>
          <span v-else class="list-view__muted">—</span>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { DeleteOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { useCalendarStore } from '@/stores/calendar'
import type { ICalendarEvent } from '@/api/calendar'
import EventBadge from './EventBadge.vue'

const store = useCalendarStore()

const emit = defineEmits<{
  (e: 'edit', event: ICalendarEvent): void
}>()

const columns = [
  { title: '时间', dataIndex: 'start_time', key: 'start_time', width: 200 },
  { title: '标题', dataIndex: 'title', key: 'title' },
  { title: '来源', dataIndex: 'source', key: 'source', width: 60 },
  { title: '类型', dataIndex: 'event_type_id', key: 'event_type_id', width: 100 },
  { title: '地点', dataIndex: 'location', key: 'location', width: 140 },
]

const sortedEvents = computed(() =>
  [...store.events].sort((a, b) => a.start_time.localeCompare(b.start_time)),
)

// --- Batch selection ---
const selectedRowKeys = ref<(string | number)[]>([])
const batchTypeId = ref<string | null>(null)
const batchTagName = ref('')

const rowSelection = {
  selectedRowKeys,
  onChange: (keys: (string | number)[]): void => {
    selectedRowKeys.value = keys
  },
}

function clearSelection(): void {
  selectedRowKeys.value = []
  batchTypeId.value = null
  batchTagName.value = ''
}

async function batchDelete(): Promise<void> {
  const count = selectedRowKeys.value.length
  try {
    for (const id of selectedRowKeys.value) {
      await store.deleteEvent(id as string)
    }
    message.success(`已删除 ${count} 个事件`)
    clearSelection()
  } catch {
    message.error('批量删除失败')
  }
}

async function batchChangeType(typeId: string | null): Promise<void> {
  if (!typeId) return
  const count = selectedRowKeys.value.length
  try {
    for (const id of selectedRowKeys.value) {
      await store.updateEvent(id as string, { event_type_id: typeId })
    }
    message.success(`已更新 ${count} 个事件的类型`)
    batchTypeId.value = null
    clearSelection()
  } catch {
    message.error('批量更新类型失败')
  }
}

function batchAddTag(): void {
  // ponytail: IUpdateEventRequest has no tag_ids; API doesn't support batch tag assignment yet.
  message.info('批量添加标签功能暂未支持（API 待扩展）')
  batchTagName.value = ''
}

function customRow(record: ICalendarEvent): Record<string, () => void> {
  return {
    onClick: () => emit('edit', record),
  }
}

function getTypeName(id: string): string {
  return store.eventTypes.find((t) => t.id === id)?.name ?? '未知'
}

function getTypeColor(id: string): string {
  return store.eventTypes.find((t) => t.id === id)?.color ?? 'blue'
}

function formatTime(iso: string): string {
  return new Intl.DateTimeFormat('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    hour12: false,
  }).format(new Date(iso))
}

function formatDateTime(iso: string): string {
  return new Intl.DateTimeFormat('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    hour12: false,
  }).format(new Date(iso))
}
</script>

<style scoped>
.list-view {
  height: 100%;
  overflow: hidden;
  padding: var(--space-3) 0;
}

.list-view__toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--space-2) var(--space-3);
  margin-bottom: var(--space-2);
  background: var(--color-primary-light, rgba(22, 119, 255, 0.06));
  border-radius: var(--radius-md);
}

.list-view__toolbar-count {
  font-size: var(--font-sm);
  color: var(--text-secondary);
}

.list-view__empty {
  padding: var(--space-8) 0;
}

.list-view__time {
  font-size: var(--font-xs);
  font-variant-numeric: tabular-nums;
  color: var(--text-secondary);
}

.list-view__time-sep {
  margin: 0 var(--space-1);
  color: var(--text-placeholder);
}

.list-view__title {
  font-weight: var(--font-weight-medium);
  color: var(--text-primary);
  display: flex;
  align-items: center;
  gap: var(--space-1);
}

.list-view__title--invited {
  font-style: italic;
}

.list-view__muted {
  color: var(--text-placeholder);
}
</style>
