<template>
  <div class="task-list">
    <div class="page-header">
      <h1 class="page-title">
        <svg class="title-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M9 11l3 3L22 4"/>
          <path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/>
        </svg>
        代办事项
      </h1>
      <div v-if="lastSyncTime > 0" class="sync-info">
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <circle cx="12" cy="12" r="10"></circle>
          <polyline points="12 6 12 12 16 14"></polyline>
        </svg>
        <span>更新时间: {{ formatSyncTime(lastSyncTime) }}</span>
      </div>
    </div>
    <div class="task-form">
      <input
        v-model="newTaskTitle"
        type="text"
        placeholder="输入新任务..."
        @keyup.enter="createTask"
        class="task-input"
      />
      <select v-model="newTaskPriority" class="task-select">
        <option value="Low">低</option>
        <option value="Medium">中</option>
        <option value="High">高</option>
      </select>
      <button @click="createTask" class="btn-add">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
          <line x1="12" y1="5" x2="12" y2="19"></line>
          <line x1="5" y1="12" x2="19" y2="12"></line>
        </svg>
      </button>
    </div>

    <div class="task-filters">
      <div class="sort-group">
        <select v-model="sortBy" class="sort-select">
          <option value="createdAt">创建时间</option>
          <option value="completedAt">完成时间</option>
          <option value="priority">优先级</option>
        </select>
        <select v-model="sortOrder" class="sort-select">
          <option value="desc">↓</option>
          <option value="asc">↑</option>
        </select>
        <span class="info-item">
          记录数:{{ filteredTasks.length }} 
        </span>
        <label class="checkbox-wrapper">
          <input 
            type="checkbox" 
            v-model="showCompleted" 
            class="checkbox-input"
          />
          <span class="checkbox-label">显示已完成</span>
        </label>
        <button class="hotkey-settings-btn" @click="openHotKeySettings" title="设置快捷键">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M18 3a3 3 0 0 0-3 3v12a3 3 0 0 0 3 3 3 3 0 0 0 3-3 3 3 0 0 0-3-3H6a3 3 0 0 0-3 3 3 3 0 0 0 3 3 3 3 0 0 0 3-3V6a3 3 0 0 0-3-3 3 3 0 0 0-3 3 3 3 0 0 0 3 3h12a3 3 0 0 0 3-3 3 3 0 0 0-3-3z"/>
          </svg>
          <span>快捷键</span>
        </button>
      </div>
    </div>

    <div v-if="filteredTasks.length === 0" class="empty">暂无任务</div>

    <div v-else class="tasks">
      <TaskItem
        v-for="task in filteredTasks"
        :key="task.id"
        :task="task"
        @updated="handleTaskUpdated"
        @deleted="handleTaskDeleted"
        @subtask-created="handleSubTaskCreated"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { taskApi } from '../api/tasks';
import TaskItem from './TaskItem.vue';
import LocalStorageService from '../services/localStorageService';
import type { Task } from '../types/task';

type SortByType = 'createdAt' | 'completedAt' | 'priority';
type SortOrderType = 'asc' | 'desc';

const newTaskTitle = ref('');
const newTaskPriority = ref<'Low' | 'Medium' | 'High'>('Medium');
const tasks = ref<Task[]>([]);
const showCompleted = ref(false);
const sortBy = ref<SortByType>('createdAt');
const sortOrder = ref<SortOrderType>('desc');
const isOnline = ref(LocalStorageService.isOnline());
const lastSyncTime = ref<number>(0);
const pendingChanges = ref<number>(0);

const handleOnlineStatus = () => {
  isOnline.value = LocalStorageService.isOnline();
};

const formatSyncTime = (timestamp: number): string => {
  const date = new Date(timestamp);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const minutes = Math.floor(diff / 60000);
  
  if (minutes < 1) {
    return '刚刚';
  } else if (minutes < 60) {
    return `${minutes}分钟前`;
  } else if (minutes < 1440) {
    const hours = Math.floor(minutes / 60);
    return `${hours}小时前`;
  } else {
    const days = Math.floor(minutes / 1440);
    return `${days}天前`;
  }
};

const syncToServer = async () => {
  try {
    const response = await taskApi.syncToServer();
    if (response.success && response.data) {
      tasks.value = response.data;
      const syncStatus = LocalStorageService.loadSyncStatus();
      lastSyncTime.value = syncStatus.lastSyncTime;
      pendingChanges.value = syncStatus.pendingChanges;
    }
  } catch (error) {
    console.error('Sync failed:', error);
    alert('同步失败');
  }
};

const filteredTasks = computed(() => {
  const rootTasks = tasks.value.filter(t => !t.parentTaskId);
  
  let filteredTasks: Task[];
  if (showCompleted.value) {
    filteredTasks = rootTasks;
  } else {
    filteredTasks = filterTasksByCompletion(rootTasks, false);
  }

  return sortTasks(filteredTasks);
});

const sortTasks = (tasks: Task[]): Task[] => {
  const priorityOrder: Record<string, number> = {
    'High': 3,
    'Medium': 2,
    'Low': 1
  };

  const sorted = [...tasks].sort((a, b) => {
    let comparison = 0;
    
    switch (sortBy.value) {
      case 'priority':
        const priorityDiff = priorityOrder[b.priority] - priorityOrder[a.priority];
        comparison = priorityDiff;
        if (comparison === 0) {
          comparison = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
        }
        break;
      case 'completedAt':
        const aCompletedAt = a.completedAt ? new Date(a.completedAt).getTime() : 0;
        const bCompletedAt = b.completedAt ? new Date(b.completedAt).getTime() : 0;
        comparison = bCompletedAt - aCompletedAt;
        if (comparison === 0) {
          comparison = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
        }
        break;
      case 'createdAt':
      default:
        comparison = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
        break;
    }

    return sortOrder.value === 'asc' ? -comparison : comparison;
  });

  sorted.forEach(task => {
    if (task.subTasks && task.subTasks.length > 0) {
      task.subTasks = sortTasks(task.subTasks);
    }
  });

  return sorted;
};

const filterTasksByCompletion = (tasks: Task[], isCompleted: boolean): Task[] => {
  return tasks.filter(task => {
    if (task.isCompleted === isCompleted) {
      return true;
    }
    if (task.subTasks && task.subTasks.length > 0) {
      const filteredSubTasks = filterTasksByCompletion(task.subTasks, isCompleted);
      if (filteredSubTasks.length > 0) {
        task.subTasks = filteredSubTasks;
        return true;
      }
    }
    return false;
  });
};

const loadTasks = async () => {
  try {
    const response = await taskApi.getTasks();
    if (response.success && response.data) {
      tasks.value = response.data;
      const syncStatus = LocalStorageService.loadSyncStatus();
      lastSyncTime.value = syncStatus.lastSyncTime;
      pendingChanges.value = syncStatus.pendingChanges;
    }
  } catch (error) {
    console.error('Failed to load tasks:', error);
    alert('加载任务失败');
  }
};

const createTask = async () => {
  if (!newTaskTitle.value.trim()) {
    alert('请输入任务标题');
    return;
  }

  try {
    const response = await taskApi.createTask({
      title: newTaskTitle.value.trim(),
      priority: newTaskPriority.value,
    });

    if (response.success && response.data) {
      tasks.value.unshift(response.data);
      newTaskTitle.value = '';
      newTaskPriority.value = 'Medium';
    }
  } catch (error) {
    console.error('Failed to create task:', error);
    alert('创建任务失败');
  }
};

const handleTaskUpdated = (updatedTask: Task) => {
  updateTaskInTree(tasks.value, updatedTask);
};

const updateTaskInTree = (tasks: Task[], updatedTask: Task): boolean => {
  for (let i = 0; i < tasks.length; i++) {
    if (tasks[i].id === updatedTask.id) {
      tasks[i] = updatedTask;
      return true;
    }
    if (tasks[i].subTasks && tasks[i].subTasks.length > 0) {
      if (updateTaskInTree(tasks[i].subTasks, updatedTask)) {
        return true;
      }
    }
  }
  return false;
};

const handleTaskDeleted = (taskId: number) => {
  deleteTaskFromTree(tasks.value, taskId);
};

const deleteTaskFromTree = (tasks: Task[], taskId: number): boolean => {
  for (let i = 0; i < tasks.length; i++) {
    if (tasks[i].id === taskId) {
      tasks.splice(i, 1);
      return true;
    }
    if (tasks[i].subTasks && tasks[i].subTasks.length > 0) {
      if (deleteTaskFromTree(tasks[i].subTasks, taskId)) {
        return true;
      }
    }
  }
  return false;
};

const handleSubTaskCreated = (subTask: Task) => {
  addSubTaskToTree(tasks.value, subTask);
};

const addSubTaskToTree = (tasks: Task[], subTask: Task): boolean => {
  for (let i = 0; i < tasks.length; i++) {
    if (tasks[i].id === subTask.parentTaskId) {
      if (!tasks[i].subTasks) {
        tasks[i].subTasks = [];
      }
      tasks[i].subTasks.push(subTask);
      return true;
    }
    if (tasks[i].subTasks && tasks[i].subTasks.length > 0) {
      if (addSubTaskToTree(tasks[i].subTasks, subTask)) {
        return true;
      }
    }
  }
  return false;
};

const openHotKeySettings = () => {
  const event = new CustomEvent('openHotKeySettings', {
    detail: {
      modifiers: 'Alt',
      key: 'X',
      isEnabled: true
    }
  });
  window.dispatchEvent(event);
};

onMounted(() => {
  loadTasks();
  handleOnlineStatus();
  window.addEventListener('online', handleOnlineStatus);
  window.addEventListener('offline', handleOnlineStatus);
});

onUnmounted(() => {
  window.removeEventListener('online', handleOnlineStatus);
  window.removeEventListener('offline', handleOnlineStatus);
});
</script>

<style scoped>
.task-list {
  max-width: 900px;
  margin: 0 auto;
  padding: 4px 12px;
  background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 100%);
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 6px 20px;
  border-radius: 20px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 28px;
  font-weight: 700;
  color: #1e293b;
  margin: 0;
}

.title-icon {
  width: 32px;
  height: 32px;
  color: #6366f1;
  background: linear-gradient(135deg, #e0e7ff 0%, #c7d2fe 100%);
  padding: 4px;
  border-radius: 10px;
}

.task-form {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
  background: white;
  padding: 8px;
  border-radius: 20px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(99, 102, 241, 0.1);
}

.task-input {
  flex: 1;
  padding: 8px;
  border: 2px solid #e2e8f0;
  border-radius: 14px;
  font-size: 14px;
  transition: all 0.3s ease;
  background: #f8fafc;
  color: #1e293b;
}

.task-input:focus {
  outline: none;
  border-color: #6366f1;
  background: white;
  box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.1);
}

.task-select {
  padding: 10px 14px;
  border: 2px solid #e2e8f0;
  border-radius: 14px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f8fafc;
  min-width: 150px;
  color: #1e293b;
}

.task-select:focus {
  outline: none;
  border-color: #6366f1;
  background: white;
  box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.1);
}

.btn-add {
  padding: 8px 16px;
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  color: white;
  border: none;
  border-radius: 14px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px -2px rgba(99, 102, 241, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-add:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 16px -2px rgba(99, 102, 241, 0.5);
}

.btn-add:active {
  transform: translateY(0);
}

.task-filters {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 12px;
  align-items: center;
  background: white;
  padding: 10px 14px;
  border-radius: 18px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(99, 102, 241, 0.05);
}

.checkbox-wrapper {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  user-select: none;
  padding: 4px 10px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-radius: 10px;
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
  margin-left: auto;
}

.checkbox-wrapper:hover {
  border-color: #6366f1;
  background: white;
}

.checkbox-input {
  width: 18px;
  height: 18px;
  cursor: pointer;
  accent-color: #6366f1;
  transition: all 0.3s ease;
}

.checkbox-label {
  font-size: 14px;
  font-weight: 500;
  color: #475569;
  cursor: pointer;
  transition: all 0.3s ease;
}

.checkbox-wrapper:hover .checkbox-label {
  color: #6366f1;
}

.task-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: default;
  user-select: none;
  padding: 4px 10px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-radius: 10px;
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
  font-size: 14px;
  font-weight: 500;
  color: #475569;
}

.info-item svg {
  flex-shrink: 0;
}

.sync-info {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 10px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-radius: 10px;
  border: 1px solid #e2e8f0;
  font-size: 12px;
  font-weight: 500;
  color: #475569;
  transition: all 0.3s ease;
}

.sync-info svg {
  flex-shrink: 0;
}

.sort-group {
  display: flex;
  gap: 4px;
  align-items: center;
}

.sort-select {
  padding: 6px 10px;
  border: 2px solid #e2e8f0;
  border-radius: 12px;
  cursor: pointer;
  font-size: 14px;
  background: #f8fafc;
  transition: all 0.3s ease;
  color: #475569;
}

.sort-select:focus {
  outline: none;
  border-color: #6366f1;
  background: white;
}

.sort-select:hover {
  border-color: #6366f1;
}

.hotkey-settings-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  color: white;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px -2px rgba(99, 102, 241, 0.4);
}

.hotkey-settings-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px -2px rgba(99, 102, 241, 0.5);
}

.hotkey-settings-btn:active {
  transform: translateY(0);
}

.hotkey-settings-btn svg {
  flex-shrink: 0;
}

.hotkey-settings-btn span {
  font-size: 14px;
}

.empty {
  text-align: center;
  padding: 40px 20px;
  color: #94a3b8;
  font-size: 16px;
  background: white;
  border-radius: 20px;
  border: 2px dashed #e2e8f0;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

.tasks {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

@media (max-width: 768px) {
  .task-list {
    padding: 10px;
    max-width: 100%;
  }

  .page-header {
    padding: 12px 16px;
    border-radius: 16px;
    margin-bottom: 10px;
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .page-title {
    font-size: 28px;
  }

  .title-icon {
    width: 32px;
    height: 32px;
  }

  .task-form {
    padding: 12px;
    border-radius: 16px;
    margin-bottom: 10px;
    gap: 6px;
  }

  .task-input {
    padding: 10px 14px;
    font-size: 14px;
    border-radius: 12px;
  }

  .task-select {
    padding: 10px 14px;
    font-size: 14px;
    min-width: 100px;
    border-radius: 12px;
  }

  .btn-add {
    padding: 10px 20px;
    font-size: 15px;
    border-radius: 12px;
  }

  .task-filters {
    padding: 10px 12px;
    border-radius: 16px;
    gap: 6px;
    margin-bottom: 10px;
    flex-direction: row;
    align-items: center;
  }

  .checkbox-wrapper {
    padding: 4px 10px;
  }

  .checkbox-input {
    width: 16px;
    height: 16px;
  }

  .checkbox-label {
    font-size: 14px;
  }

  .sort-group {
    width: auto;
    justify-content: flex-start;
  }

  .sort-select {
    padding: 5px 8px;
    font-size: 14px;
    flex: none;
  }

  .hotkey-settings-btn {
    padding: 5px 10px;
    font-size: 13px;
    border-radius: 10px;
  }

  .hotkey-settings-btn svg {
    width: 16px;
    height: 16px;
  }

  .task-info {
    width: auto;
    justify-content: flex-start;
  }

  .info-item {
    padding: 4px 10px;
    font-size: 12px;
  }

  .empty {
    padding: 30px 16px;
    font-size: 16px;
    border-radius: 16px;
  }

  .tasks {
    gap: 6px;
  }
}

@media (max-width: 480px) {
  .task-list {
    padding: 8px;
  }

  .page-header {
    padding: 10px 14px;
    border-radius: 14px;
    margin-bottom: 8px;
  }

  .page-title {
    font-size: 28px;
  }

  .title-icon {
    width: 32px;
    height: 32px;
    padding: 4px;
  }

  .task-form {
    padding: 10px;
    border-radius: 14px;
    margin-bottom: 8px;
    gap: 6px;
  }

  .task-input {
    padding: 8px 12px;
    font-size: 15px;
    border-radius: 10px;
  }

  .task-select {
    padding: 8px 12px;
    font-size: 15px;
    min-width: 80px;
    border-radius: 10px;
  }

  .btn-add {
    padding: 8px 16px;
    font-size: 15px;
    border-radius: 10px;
  }

  .btn-add svg {
    width: 14px;
    height: 14px;
  }

  .task-filters {
    padding: 8px 10px;
    border-radius: 14px;
    gap: 6px;
    margin-bottom: 8px;
    flex-direction: row;
    align-items: center;
  }

  .checkbox-wrapper {
    padding: 4px 8px;
  }

  .checkbox-input {
    width: 16px;
    height: 16px;
  }

  .checkbox-label {
    font-size: 14px;
  }

  .sort-group {
    width: auto;
    justify-content: flex-start;
  }

  .sort-select {
    padding: 4px 8px;
    font-size: 14px;
    flex: none;
  }

  .hotkey-settings-btn {
    padding: 4px 8px;
    font-size: 12px;
    border-radius: 8px;
  }

  .hotkey-settings-btn svg {
    width: 14px;
    height: 14px;
  }

  .hotkey-settings-btn span {
    display: none;
  }

  .task-info {
    width: auto;
    justify-content: flex-start;
  }

  .info-item {
    padding: 4px 8px;
    font-size: 14px;
  }

  .info-item svg {
    width: 10px;
    height: 10px;
  }

  .empty {
    padding: 25px 12px;
    font-size: 16px;
    border-radius: 14px;
  }

  .tasks {
    gap: 6px;
  }
}
</style>
