<template>
  <a-drawer
    :open="open"
    @close="close"
    placement="right"
    :width="480"
    title="邀请管理"
    :destroyOnClose="true"
  >
    <!-- Event selector + invitees for selected event -->
    <div class="invitation-manager__section">
      <div class="invitation-manager__section-header">
        <span class="invitation-manager__section-title">事件邀请</span>
        <a-button
          v-if="selectedEventId"
          size="small"
          type="primary"
          @click="inviteModalOpen = true"
        >
          <template #icon><PlusOutlined /></template>
          邀请
        </a-button>
      </div>

      <a-select
        v-model:value="selectedEventId"
        allowClear
        placeholder="选择事件以管理邀请"
        style="width: 100%; margin-bottom: 12px"
        @change="loadEventInvitations"
      >
        <a-select-option v-for="ev in store.events" :key="ev.id" :value="ev.id">
          {{ ev.title }}
        </a-select-option>
      </a-select>

      <template v-if="selectedEventId">
        <a-empty v-if="eventInvitations.length === 0" description="暂无邀请" />
        <a-list v-else :dataSource="eventInvitations" size="small">
          <template #renderItem="{ item }">
            <a-list-item>
              <a-list-item-meta>
                <template #title>{{ item.invitee_email }}</template>
                <template #description>
                  <a-tag :color="statusColor(item.status)">{{ statusLabel(item.status) }}</a-tag>
                </template>
              </a-list-item-meta>
            </a-list-item>
          </template>
        </a-list>
      </template>
    </div>

    <a-divider />

    <!-- Incoming invitations (G6) -->
    <div class="invitation-manager__section">
      <div class="invitation-manager__section-header">
        <span class="invitation-manager__section-title">收到的邀请</span>
        <a-badge :count="store.pendingInvitations.length" />
      </div>
      <a-empty v-if="store.pendingInvitations.length === 0" description="暂无待处理邀请" />
      <a-list v-else :dataSource="store.pendingInvitations" size="small">
        <template #renderItem="{ item }">
          <a-list-item>
            <a-list-item-meta>
              <template #title>{{ invitationEventTitle(item.event_id) }}</template>
              <template #description>{{ item.invitee_email }}</template>
            </a-list-item-meta>
            <template #actions>
              <a-space>
                <a-button size="small" type="primary" @click="respond(item.id, 'accepted')">
                  接受
                </a-button>
                <a-button size="small" @click="respond(item.id, 'tentative')">待定</a-button>
                <a-button size="small" danger @click="respond(item.id, 'declined')">
                  拒绝
                </a-button>
              </a-space>
            </template>
          </a-list-item>
        </template>
      </a-list>
    </div>

    <!-- User search modal for inviting (G5/A3) -->
    <a-modal v-model:open="inviteModalOpen" title="邀请用户" :footer="null" :width="420">
      <a-input-search
        v-model:value="searchQuery"
        placeholder="搜索用户名或邮箱"
        @search="doSearch"
        :loading="searching"
      />
      <a-list
        v-if="searchResults.length > 0"
        :dataSource="searchResults"
        size="small"
        class="invitation-manager__search-results"
      >
        <template #renderItem="{ item }">
          <a-list-item>
            <a-list-item-meta>
              <template #title>{{ item.username }}</template>
              <template #description>{{ item.email }}</template>
            </a-list-item-meta>
            <template #actions>
              <a-button
                size="small"
                type="primary"
                :loading="invitingEmail === item.email"
                @click="inviteUser(item.email)"
              >
                邀请
              </a-button>
            </template>
          </a-list-item>
        </template>
      </a-list>
    </a-modal>
  </a-drawer>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { useCalendarStore } from '@/stores/calendar'
import { calendarApi } from '@/api/calendar'
import type { ICalendarEvent, IInvitation, IUserSearchResult } from '@/api/calendar'

const props = defineProps<{
  open: boolean
  event: ICalendarEvent | null
}>()

const emit = defineEmits<{
  (e: 'update:open', value: boolean): void
}>()

const store = useCalendarStore()

const selectedEventId = ref<string | null>(null)
const eventInvitations = ref<IInvitation[]>([])
const inviteModalOpen = ref(false)
const searchQuery = ref('')
const searchResults = ref<IUserSearchResult[]>([])
const searching = ref(false)
const invitingEmail = ref<string | null>(null)

// Sync event prop to internal selection
watch(
  () => [props.open, props.event],
  () => {
    if (!props.open) return
    selectedEventId.value = props.event?.id ?? null
    if (selectedEventId.value) {
      loadEventInvitations()
    } else {
      eventInvitations.value = []
    }
  },
  { immediate: true },
)

function close(): void {
  emit('update:open', false)
}

async function loadEventInvitations(): Promise<void> {
  if (!selectedEventId.value) {
    eventInvitations.value = []
    return
  }
  try {
    const resp = await calendarApi.listInvitations()
    eventInvitations.value = (resp.invitations || []).filter(
      (i) => i.event_id === selectedEventId.value,
    )
  } catch (err) {
    console.warn('Failed to load event invitations:', err)
  }
}

async function doSearch(): Promise<void> {
  if (!searchQuery.value.trim()) return
  searching.value = true
  try {
    searchResults.value = await store.searchUsers(searchQuery.value)
  } finally {
    searching.value = false
  }
}

async function inviteUser(email: string): Promise<void> {
  if (!selectedEventId.value) return
  invitingEmail.value = email
  try {
    await calendarApi.createInvitation({
      event_id: selectedEventId.value,
      invitee_email: email,
    })
    message.success(`已邀请 ${email}`)
    await loadEventInvitations()
  } catch {
    message.error('邀请失败')
  } finally {
    invitingEmail.value = null
  }
}

async function respond(
  id: string,
  status: 'accepted' | 'declined' | 'tentative',
): Promise<void> {
  try {
    await store.respondToInvitation(id, status)
    message.success(status === 'accepted' ? '已接受' : status === 'declined' ? '已拒绝' : '已标记待定')
  } catch {
    message.error('操作失败')
  }
}

function invitationEventTitle(eventId: string): string {
  return store.events.find((e) => e.id === eventId)?.title ?? '未知事件'
}

function statusColor(status: IInvitation['status']): string {
  switch (status) {
    case 'accepted':
      return 'green'
    case 'declined':
      return 'red'
    case 'tentative':
      return 'orange'
    default:
      return 'default'
  }
}

function statusLabel(status: IInvitation['status']): string {
  switch (status) {
    case 'accepted':
      return '已接受'
    case 'declined':
      return '已拒绝'
    case 'tentative':
      return '待定'
    default:
      return '待回复'
  }
}
</script>

<style scoped>
.invitation-manager__section {
  margin-bottom: var(--space-3);
}

.invitation-manager__section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--space-2);
}

.invitation-manager__section-title {
  font-size: var(--font-sm);
  font-weight: var(--font-weight-medium);
  color: var(--text-primary);
}

.invitation-manager__search-results {
  margin-top: var(--space-3);
}
</style>
