<template>
  <div class="reminder-config">
    <a-alert
      type="info"
      show-icon
      message="为每种事件类型配置默认提醒规则。新建事件时将由后端（U5）自动继承对应规则。"
      style="margin-bottom: var(--space-3)"
    />

    <a-form layout="inline" style="margin-bottom: var(--space-3)">
      <a-form-item label="事件类型">
        <a-select
          :value="selectedTypeId"
          style="width: 220px"
          placeholder="选择事件类型"
          :options="typeOptions"
          allow-clear
          @change="onTypeChange"
        />
      </a-form-item>
    </a-form>

    <div v-if="!selectedTypeId" class="reminder-config__empty">
      <BellOutlined />
      <span>请选择事件类型以配置提醒规则</span>
    </div>

    <div v-else class="reminder-config__rules">
      <div v-if="draftRules.length === 0" class="reminder-config__empty">
        <BellOutlined />
        <span>暂无提醒规则</span>
      </div>

      <div v-else class="reminder-config__rule-list">
        <div
          v-for="(rule, index) in draftRules"
          :key="index"
          class="reminder-config__rule"
        >
          <span class="reminder-config__rule-offset">
            <ClockCircleOutlined />
            {{ rule.offset_minutes }} 分钟前
          </span>
          <div class="reminder-config__rule-channels">
            <a-tag
              v-for="ch in rule.channels"
              :key="ch"
              :color="channelColor(ch)"
            >
              {{ channelLabel(ch) }}
            </a-tag>
          </div>
          <a-button type="link" danger size="small" @click="removeRule(index)">
            <template #icon><DeleteOutlined /></template>
            移除
          </a-button>
        </div>
      </div>

      <a-divider style="margin: var(--space-3) 0" />

      <div class="reminder-config__add">
        <a-input-number
          v-model:value="newOffset"
          :min="0"
          :step="5"
          addon-before="提前"
          addon-after="分钟"
          style="width: 200px"
        />
        <a-checkbox-group v-model:value="newChannels" :options="channelOptions" />
        <a-button type="primary" :disabled="!canAdd" @click="addRule">
          <template #icon><PlusOutlined /></template>
          添加规则
        </a-button>
      </div>

      <div style="margin-top: var(--space-4)">
        <a-button type="primary" @click="save">
          <template #icon><CheckCircleOutlined /></template>
          保存规则
        </a-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { notification } from 'ant-design-vue'
import {
  BellOutlined,
  PlusOutlined,
  DeleteOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
} from '@ant-design/icons-vue'
import { useCalendarStore } from '@/stores/calendar'

type ReminderChannel = 'client' | 'email' | 'webhook'

interface IReminderRule {
  offset_minutes: number
  channels: ReminderChannel[]
}

const STORAGE_KEY = 'calendar:reminder-rules'

const channelOptions: Array<{ label: string; value: ReminderChannel }> = [
  { label: '客户端', value: 'client' },
  { label: '邮件', value: 'email' },
  { label: 'Webhook', value: 'webhook' },
]

// ponytail: backend endpoint for per-event-type reminder rule CRUD is
// deferred — U5 inherits rules at event creation time. Until the CRUD
// route lands, rules are persisted locally in localStorage (native
// platform feature, no new deps). Functional but per-device; the upgrade
// path is a GET/PUT /event-types/{id}/reminder-rules endpoint.
function loadRules(): Record<string, IReminderRule[]> {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    return raw ? (JSON.parse(raw) as Record<string, IReminderRule[]>) : {}
  } catch {
    return {}
  }
}

function persistRules(rules: Record<string, IReminderRule[]>): void {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(rules))
  } catch {
    /* quota / private mode — non-fatal, rules stay in-memory for the session */
  }
}

const store = useCalendarStore()

const allRules = ref<Record<string, IReminderRule[]>>(loadRules())
const selectedTypeId = ref<string | null>(null)
const draftRules = ref<IReminderRule[]>([])
const newOffset = ref(15)
const newChannels = ref<ReminderChannel[]>(['client'])

const typeOptions = computed(() =>
  store.eventTypes.map((t) => ({ label: t.name, value: t.id })),
)

const canAdd = computed(() => newChannels.value.length > 0 && newOffset.value >= 0)

// When the selected type changes, load its rules into the working draft.
watch(
  selectedTypeId,
  (id) => {
    if (!id) {
      draftRules.value = []
      return
    }
    draftRules.value = (allRules.value[id] ?? []).map((r) => ({
      offset_minutes: r.offset_minutes,
      channels: [...r.channels],
    }))
  },
  { immediate: true },
)

function onTypeChange(id: string | undefined): void {
  selectedTypeId.value = id ?? null
}

function addRule(): void {
  if (!canAdd.value) return
  draftRules.value.push({
    offset_minutes: newOffset.value,
    channels: [...newChannels.value],
  })
}

function removeRule(index: number): void {
  draftRules.value.splice(index, 1)
}

function save(): void {
  if (!selectedTypeId.value) return
  allRules.value[selectedTypeId.value] = draftRules.value.map((r) => ({
    offset_minutes: r.offset_minutes,
    channels: [...r.channels],
  }))
  persistRules(allRules.value)
  notification.success({ message: '提醒规则已保存' })
}

function channelLabel(ch: ReminderChannel): string {
  return channelOptions.find((o) => o.value === ch)?.label ?? ch
}

function channelColor(ch: ReminderChannel): string {
  return ch === 'client' ? 'blue' : ch === 'email' ? 'green' : 'orange'
}

onMounted(() => {
  // ponytail: Tauri system-notification integration (showing native OS
  // notifications for calendar_reminder WS events) is deferred — the
  // store currently surfaces reminders via ant-design notification only.
  if (store.eventTypes.length === 0) {
    store.loadEventTypes()
  }
})
</script>

<style scoped>
.reminder-config {
  padding: var(--space-2) 0;
}

.reminder-config__empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: var(--space-2);
  padding: var(--space-6) 0;
  color: var(--text-tertiary);
  font-size: var(--font-sm);
}

.reminder-config__rule-list {
  display: flex;
  flex-direction: column;
  gap: var(--space-2);
}

.reminder-config__rule {
  display: flex;
  align-items: center;
  gap: var(--space-3);
  padding: var(--space-2) var(--space-3);
  border: 1px solid var(--border-color-split);
  border-radius: var(--radius-md);
}

.reminder-config__rule-offset {
  display: flex;
  align-items: center;
  gap: var(--space-1);
  font-size: var(--font-sm);
  color: var(--text-primary);
  font-variant-numeric: tabular-nums;
  min-width: 120px;
}

.reminder-config__rule-channels {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  gap: var(--space-1);
}

.reminder-config__add {
  display: flex;
  align-items: center;
  gap: var(--space-3);
  flex-wrap: wrap;
}
</style>
