<script setup>
import { ref, watch, computed, onMounted, onUnmounted } from 'vue'
import { useCalendar } from '../composables/useCalendar'
import ConfirmDialog from './ConfirmDialog.vue'

const props = defineProps({
  event: {
    type: Object,
    default: null
  },
  selectedDate: {
    type: String,
    default: null
  }
})

const emit = defineEmits(['close', 'save', 'delete'])

const { teamMembers } = useCalendar()

// 显示删除确认弹窗
const showDeleteConfirm = ref(false)

// 表单数据
const formData = ref({
  memberId: null,
  title: '',
  description: '',
  startDate: '',
  endDate: '',
  startTime: '09:00',
  endTime: '18:00',
})

// 将日期格式化为本地时间的 YYYY-MM-DD 字符串（避免时区问题）
function formatLocalDate(date) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 初始化表单
watch(() => props.event, (event) => {
  if (event) {
    formData.value = { ...event }
  } else {
    const today = props.selectedDate || formatLocalDate(new Date())
    formData.value = {
      memberId: teamMembers.value[0]?.id || null,
      title: '',
      description: '',
      startDate: today,
      endDate: today,
      startTime: '09:00',
      endTime: '18:00',
    }
  }
}, { immediate: true })

// 是否是编辑模式
const isEditing = computed(() => !!props.event)

// 表单验证
const isValid = computed(() => {
  return formData.value.memberId &&
    formData.value.title.trim() &&
    formData.value.startDate &&
    formData.value.endDate &&
    formData.value.startTime &&
    formData.value.endTime &&
    formData.value.startDate <= formData.value.endDate
})

// 提交表单
function handleSubmit() {
  if (!isValid.value) return
  emit('save', { ...formData.value })
}

// 显示删除确认
function showDeleteDialog() {
  showDeleteConfirm.value = true
}

// 确认删除
function confirmDelete() {
  showDeleteConfirm.value = false
  if (props.event) {
    emit('delete', props.event.id)
  }
}

// 取消删除
function cancelDelete() {
  showDeleteConfirm.value = false
}

// ESC键关闭
function handleKeydown(e) {
  if (e.key === 'Escape') {
    emit('close')
  }
}

onMounted(() => {
  document.addEventListener('keydown', handleKeydown)
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
})

// 获取成员颜色
function getMemberColor(memberId) {
  const member = teamMembers.value.find(m => m.id === memberId)
  return member?.color || 'var(--color-primary)'
}
</script>

<template>
  <div class="modal-overlay" @click.self="emit('close')">
    <div class="modal-content glass-card animate-scaleIn">
      <!-- 头部 -->
      <div class="modal-header">
        <h3 class="modal-title">
          {{ isEditing ? '编辑任务' : '添加任务' }}
        </h3>
        <button class="btn btn-icon close-btn" @click="emit('close')">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M18 6L6 18M6 6l12 12"/>
          </svg>
        </button>
      </div>

      <!-- 表单 -->
      <form class="modal-body" @submit.prevent="handleSubmit">
        <!-- 选择成员 -->
        <div class="form-group">
          <label class="label">团队成员</label>
          <div class="member-selector">
            <button
              v-for="member in teamMembers"
              :key="member.id"
              type="button"
              class="member-option"
              :class="{ selected: formData.memberId === member.id }"
              :style="{ '--member-color': member.color }"
              @click="formData.memberId = member.id"
            >
              <div class="member-avatar">{{ member.avatar }}</div>
              <span class="member-name">{{ member.name }}</span>
            </button>
          </div>
        </div>

        <!-- 任务标题 -->
        <div class="form-group">
          <label class="label" for="title">任务标题</label>
          <input
            id="title"
            v-model="formData.title"
            type="text"
            class="input"
            placeholder="输入任务标题..."
            required
          />
        </div>

        <!-- 任务描述 -->
        <div class="form-group">
          <label class="label" for="description">任务描述</label>
          <textarea
            id="description"
            v-model="formData.description"
            class="input"
            placeholder="输入任务描述..."
            rows="3"
          ></textarea>
        </div>

        <!-- 日期选择 -->
        <div class="form-row">
          <div class="form-group">
            <label class="label" for="startDate">开始日期</label>
            <input
              id="startDate"
              v-model="formData.startDate"
              type="date"
              class="input"
              required
            />
          </div>
          <div class="form-group">
            <label class="label" for="endDate">结束日期</label>
            <input
              id="endDate"
              v-model="formData.endDate"
              type="date"
              class="input"
              required
            />
          </div>
        </div>

        <!-- 时间选择 -->
        <div class="form-row">
          <div class="form-group">
            <label class="label" for="startTime">开始时间</label>
            <input
              id="startTime"
              v-model="formData.startTime"
              type="time"
              class="input"
              required
            />
          </div>
          <div class="form-group">
            <label class="label" for="endTime">结束时间</label>
            <input
              id="endTime"
              v-model="formData.endTime"
              type="time"
              class="input"
              required
            />
          </div>
        </div>

        <!-- 预览 -->
        <div 
          v-if="formData.memberId && formData.title"
          class="preview-card"
          :style="{ '--preview-color': getMemberColor(formData.memberId) }"
        >
          <div class="preview-indicator"></div>
          <div class="preview-content">
            <span class="preview-title">{{ formData.title }}</span>
            <span class="preview-time">
              {{ formData.startDate }} · {{ formData.startTime }} - {{ formData.endTime }}
            </span>
          </div>
        </div>
      </form>

      <!-- 底部按钮 -->
      <div class="modal-footer">
        <button 
          v-if="isEditing"
          type="button" 
          class="btn delete-btn"
          @click="showDeleteDialog"
        >
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M3 6h18M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"/>
          </svg>
          删除
        </button>
        <div class="footer-actions">
          <button type="button" class="btn" @click="emit('close')">
            取消
          </button>
          <button 
            type="submit" 
            class="btn btn-primary"
            :disabled="!isValid"
            @click="handleSubmit"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M5 12l5 5L20 7"/>
            </svg>
            {{ isEditing ? '保存更改' : '添加任务' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <ConfirmDialog
      :show="showDeleteConfirm"
      type="danger"
      title="删除任务"
      :message="`确定要删除「${formData.title}」吗？此操作无法撤销。`"
      confirm-text="删除"
      cancel-text="取消"
      @confirm="confirmDelete"
      @cancel="cancelDelete"
    />
  </div>
</template>

<style scoped>
.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(4px);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-lg);
  z-index: 1000;
  /* 移动端优化 */
  overscroll-behavior: contain;
  touch-action: none;
}

.modal-content {
  width: 100%;
  max-width: 520px;
  /* 使用 dvh 作为首选，100vh 作为回退 */
  max-height: 90vh;
  max-height: 90dvh;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  background: rgba(255, 255, 255, 0.95);
  /* 移动端滚动优化 */
  -webkit-overflow-scrolling: touch;
  overscroll-behavior: contain;
  touch-action: pan-y;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--spacing-lg);
  border-bottom: 1px solid rgba(0, 0, 0, 0.08);
}

.modal-title {
  font-family: var(--font-heading);
  font-size: 1.25rem;
  font-weight: 600;
  color: var(--color-text);
}

.close-btn {
  margin: calc(-1 * var(--spacing-sm));
}

.modal-body {
  padding: var(--spacing-lg);
  display: flex;
  flex-direction: column;
  gap: var(--spacing-lg);
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: var(--spacing-md);
}

/* 成员选择器 */
.member-selector {
  display: flex;
  flex-wrap: wrap;
  gap: var(--spacing-sm);
}

.member-option {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  padding: var(--spacing-xs) var(--spacing-sm);
  background: rgba(255, 255, 255, 0.8);
  border: 2px solid rgba(0, 0, 0, 0.08);
  border-radius: var(--radius-md);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.member-option:hover {
  border-color: var(--member-color);
  background: rgba(255, 255, 255, 0.95);
}

.member-option.selected {
  border-color: var(--member-color);
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.member-option .member-avatar {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.625rem;
  font-weight: 600;
  color: white;
  background: var(--member-color);
}

.member-option .member-name {
  font-size: 0.813rem;
  font-weight: 500;
  color: var(--color-text);
}

/* 预览卡片 */
.preview-card {
  display: flex;
  gap: var(--spacing-sm);
  padding: var(--spacing-md);
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.08);
  border-radius: var(--radius-md);
}

.preview-indicator {
  width: 4px;
  background: var(--preview-color);
  border-radius: 2px;
}

.preview-content {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.preview-title {
  font-size: 0.875rem;
  font-weight: 500;
  color: var(--color-text);
}

.preview-time {
  font-size: 0.75rem;
  color: var(--color-text-muted);
}

/* 底部 */
.modal-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--spacing-lg);
  border-top: 1px solid rgba(0, 0, 0, 0.08);
}

.footer-actions {
  display: flex;
  gap: var(--spacing-sm);
  margin-left: auto;
}

.delete-btn {
  color: #EF4444;
  border-color: rgba(239, 68, 68, 0.3);
}

.delete-btn:hover {
  background: rgba(239, 68, 68, 0.1);
  border-color: rgba(239, 68, 68, 0.5);
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 响应式 */
@media (max-width: 768px) {
  .modal-overlay {
    padding: 0;
    align-items: flex-end;
  }
  
  .modal-content {
    max-height: 85vh;
    max-height: 85dvh;
    border-radius: var(--radius-xl) var(--radius-xl) 0 0;
    /* 安全区域适配 */
    padding-bottom: env(safe-area-inset-bottom, 0);
  }
  
  .modal-header {
    position: sticky;
    top: 0;
    background: rgba(255, 255, 255, 0.98);
    backdrop-filter: blur(10px);
    z-index: 10;
    /* 增加顶部拖动指示条 */
    padding-top: calc(var(--spacing-lg) + 12px);
  }
  
  .modal-header::before {
    content: '';
    position: absolute;
    top: 8px;
    left: 50%;
    transform: translateX(-50%);
    width: 40px;
    height: 4px;
    background: rgba(0, 0, 0, 0.15);
    border-radius: 2px;
  }
  
  .modal-body {
    flex: 1;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
  }
  
  .form-row {
    grid-template-columns: 1fr;
  }
  
  .member-selector {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    max-height: 200px;
    overflow-y: auto;
  }
  
  .modal-footer {
    flex-direction: column;
    gap: var(--spacing-md);
    position: sticky;
    bottom: 0;
    background: rgba(255, 255, 255, 0.98);
    backdrop-filter: blur(10px);
    z-index: 10;
  }
  
  .footer-actions {
    width: 100%;
    margin-left: 0;
  }
  
  .footer-actions .btn {
    flex: 1;
    padding: 14px;
  }
  
  .delete-btn {
    width: 100%;
    padding: 14px;
  }
}

/* 小屏幕手机优化 */
@media (max-width: 480px) {
  .modal-content {
    max-height: 90vh;
    max-height: 90dvh;
  }
  
  .member-selector {
    grid-template-columns: 1fr;
  }
  
  .member-option {
    padding: var(--spacing-sm);
  }
}
</style>
