<template>
  <a-drawer
    :open="open"
    @close="close"
    placement="right"
    :width="560"
    :title="isEdit ? '编辑事件' : '新建事件'"
    :destroyOnClose="true"
  >
    <a-form layout="vertical">
      <a-form-item label="标题" required>
        <a-input v-model:value="form.title" placeholder="事件标题" />
      </a-form-item>

      <a-form-item label="描述">
        <a-textarea v-model:value="form.description" :rows="3" placeholder="事件描述" />
      </a-form-item>

      <a-form-item label="全天">
        <a-switch v-model:checked="form.is_all_day" />
      </a-form-item>

      <a-form-item label="日期范围" required>
        <a-range-picker v-model:value="dateRange" style="width: 100%" />
      </a-form-item>

      <a-form-item v-if="!form.is_all_day" label="时间">
        <a-space>
          <a-time-picker v-model:value="startTime" format="HH:mm" :allowClear="false" />
          <span>至</span>
          <a-time-picker v-model:value="endTime" format="HH:mm" :allowClear="false" />
        </a-space>
      </a-form-item>

      <a-form-item label="地点">
        <a-input v-model:value="form.location" placeholder="事件地点" />
      </a-form-item>

      <a-form-item label="事件类型">
        <a-select v-model:value="form.event_type_id" allowClear placeholder="选择类型">
          <a-select-option v-for="t in store.eventTypes" :key="t.id" :value="t.id">
            <a-tag :color="t.color" size="small">{{ t.name }}</a-tag>
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="标签">
        <a-select
          v-model:value="selectedTagIds"
          mode="tags"
          placeholder="选择或输入标签"
          :token-separators="[',']"
        >
          <a-select-option v-for="t in store.tags" :key="t.id" :value="t.id">
            {{ t.name }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="重复">
        <a-space>
          <a-select v-model:value="rruleFreq" style="width: 120px">
            <a-select-option value="none">不重复</a-select-option>
            <a-select-option value="DAILY">每天</a-select-option>
            <a-select-option value="WEEKLY">每周</a-select-option>
            <a-select-option value="MONTHLY">每月</a-select-option>
          </a-select>
          <template v-if="rruleFreq !== 'none'">
            <span>每</span>
            <a-input-number v-model:value="rruleInterval" :min="1" :max="99" />
            <span>{{ freqUnitLabel }}</span>
          </template>
        </a-space>
      </a-form-item>

      <a-form-item label="提醒">
        <!-- ponytail: reminders UI is local-only; ICreateEventRequest has no reminders field yet.
             Upgrade path: add reminders array to ICreateEventRequest/IUpdateEventRequest when backend supports it. -->
        <div v-for="(r, i) in reminders" :key="i" class="event-editor__reminder">
          <a-input-number v-model:value="r.offset" :min="0" addon-before="提前" addon-after="分钟" />
          <a-select v-model:value="r.channel" style="width: 100px">
            <a-select-option value="in_app">应用内</a-select-option>
            <a-select-option value="email">邮件</a-select-option>
          </a-select>
          <a-button danger size="small" @click="reminders.splice(i, 1)">
            <template #icon><DeleteOutlined /></template>
          </a-button>
        </div>
        <a-button size="small" @click="reminders.push({ offset: 15, channel: 'in_app' })">
          <template #icon><PlusOutlined /></template>
          添加提醒
        </a-button>
      </a-form-item>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="close">取消</a-button>
        <a-button type="primary" :loading="store.isLoading" @click="onSave">保存</a-button>
      </a-space>
    </template>
  </a-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import dayjs, { type Dayjs } from 'dayjs'
import { message } from 'ant-design-vue'
import { useCalendarStore } from '@/stores/calendar'
import type { ICalendarEvent, ICreateEventRequest, IUpdateEventRequest } from '@/api/calendar'

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

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

const store = useCalendarStore()

const isEdit = computed(() => !!props.event)

interface ReminderRule {
  offset: number
  channel: 'in_app' | 'email'
}

const form = reactive({
  title: '',
  description: '',
  is_all_day: false,
  location: '',
  event_type_id: null as string | null,
})

const dateRange = ref<[Dayjs, Dayjs] | null>(null)
const startTime = ref<Dayjs>(dayjs().hour(9).minute(0).second(0))
const endTime = ref<Dayjs>(dayjs().hour(10).minute(0).second(0))
const selectedTagIds = ref<string[]>([])
const rruleFreq = ref<'none' | 'DAILY' | 'WEEKLY' | 'MONTHLY'>('none')
const rruleInterval = ref(1)
const reminders = ref<ReminderRule[]>([])

const freqUnitLabel = computed(() => {
  switch (rruleFreq.value) {
    case 'DAILY':
      return '天'
    case 'WEEKLY':
      return '周'
    case 'MONTHLY':
      return '月'
    default:
      return ''
  }
})

// Initialize form when drawer opens or event changes
watch(
  () => [props.open, props.event],
  () => {
    if (!props.open) return
    if (props.event) {
      // Edit mode — pre-fill from event
      form.title = props.event.title
      form.description = props.event.description
      form.is_all_day = props.event.is_all_day
      form.location = props.event.location
      form.event_type_id = props.event.event_type_id

      const start = dayjs(props.event.start_time)
      const end = dayjs(props.event.end_time)
      dateRange.value = [start.startOf('day'), end.startOf('day')]
      startTime.value = start
      endTime.value = end

      parseRrule(props.event.rrule)
      // ponytail: ICalendarEvent has no tags field; can't pre-fill tag selection.
      selectedTagIds.value = []
      reminders.value = []
    } else {
      // Create mode
      form.title = ''
      form.description = ''
      form.is_all_day = false
      form.location = ''
      form.event_type_id = null

      const start = props.prefillStart ? dayjs(props.prefillStart) : dayjs().hour(9).minute(0)
      const end = props.prefillEnd ? dayjs(props.prefillEnd) : start.add(1, 'hour')
      dateRange.value = [start.startOf('day'), end.startOf('day')]
      startTime.value = start
      endTime.value = end

      rruleFreq.value = 'none'
      rruleInterval.value = 1
      selectedTagIds.value = []
      reminders.value = []
    }
  },
  { immediate: true },
)

function parseRrule(rrule: string | null): void {
  if (!rrule) {
    rruleFreq.value = 'none'
    rruleInterval.value = 1
    return
  }
  const freqMatch = rrule.match(/FREQ=(\w+)/)
  const intervalMatch = rrule.match(/INTERVAL=(\d+)/)
  if (freqMatch && ['DAILY', 'WEEKLY', 'MONTHLY'].includes(freqMatch[1])) {
    rruleFreq.value = freqMatch[1] as 'DAILY' | 'WEEKLY' | 'MONTHLY'
    rruleInterval.value = intervalMatch ? parseInt(intervalMatch[1], 10) : 1
  } else {
    rruleFreq.value = 'none'
    rruleInterval.value = 1
  }
}

function buildRrule(): string | null {
  if (rruleFreq.value === 'none') return null
  return `FREQ=${rruleFreq.value};INTERVAL=${rruleInterval.value}`
}

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

/** Resolve tag selections to IDs, creating new tags as needed */
async function resolveTagIds(): Promise<string[]> {
  const ids: string[] = []
  for (const val of selectedTagIds.value) {
    const existing = store.tags.find((t) => t.id === val)
    if (existing) {
      ids.push(existing.id)
    } else {
      // New tag name typed by user — create it
      const tag = await store.createTag({ name: val })
      if (tag) ids.push(tag.id)
    }
  }
  return ids
}

async function onSave(): Promise<void> {
  if (!form.title.trim()) {
    message.warning('请输入标题')
    return
  }
  if (!dateRange.value) {
    message.warning('请选择日期范围')
    return
  }

  const [startDate, endDate] = dateRange.value
  let startIso: string
  let endIso: string

  if (form.is_all_day) {
    startIso = startDate.startOf('day').toISOString()
    endIso = endDate.startOf('day').toISOString()
  } else {
    // KTD-11: combine local date + time, convert to UTC ISO 8601
    startIso = startDate
      .hour(startTime.value.hour())
      .minute(startTime.value.minute())
      .second(0)
      .millisecond(0)
      .toISOString()
    endIso = endDate
      .hour(endTime.value.hour())
      .minute(endTime.value.minute())
      .second(0)
      .millisecond(0)
      .toISOString()
  }

  const rrule = buildRrule()

  try {
    if (props.event) {
      const updateData: IUpdateEventRequest = {
        title: form.title,
        description: form.description,
        start_time: startIso,
        end_time: endIso,
        is_all_day: form.is_all_day,
        location: form.location,
        event_type_id: form.event_type_id,
        rrule,
      }
      await store.updateEvent(props.event.id, updateData)
      message.success('事件已更新')
      emit('saved', props.event)
    } else {
      const tagIds = await resolveTagIds()
      const createData: ICreateEventRequest = {
        title: form.title,
        description: form.description,
        start_time: startIso,
        end_time: endIso,
        is_all_day: form.is_all_day,
        location: form.location,
        event_type_id: form.event_type_id,
        rrule,
        tag_ids: tagIds,
      }
      const created = await store.createEvent(createData)
      message.success('事件已创建')
      if (created) emit('saved', created)
    }
    close()
  } catch {
    message.error(props.event ? '更新失败' : '创建失败')
  }
}
</script>

<style scoped>
.event-editor__reminder {
  display: flex;
  align-items: center;
  gap: var(--space-2);
  margin-bottom: var(--space-2);
}
</style>
