<template>
  <div class="task-list">
    <div class="page-header">
      <div class="header-controls">
        <div class="sort-group">
          <select v-model="sortBy" class="sort-select">
            <option value="createdAt">创建时间</option>
            <option value="completedAt">完成时间</option>
            <option value="priority">优先级</option>
          </select>
          <button
            type="button"
            class="sort-select sort-order-btn"
            @click="toggleSortOrder"
            :title="sortOrder === 'desc' ? '切换为升序' : '切换为降序'"
          >
            <svg
              v-if="sortOrder === 'desc'"
              class="sort-order-icon"
              viewBox="0 0 24 24"
              fill="currentColor"
            >
              <path d="M11 4h2v11h3l-4 4-4-4h3V4z" />
            </svg>
            <svg
              v-else
              class="sort-order-icon"
              viewBox="0 0 24 24"
              fill="currentColor"
            >
              <path d="M11 20h2V9h3l-4-4-4 4h3v11z" />
            </svg>
          </button>
          <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="16" height="16" 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 class="task-info">
        <span class="info-item">计数:{{ filteredTasks.length }}</span>
        <span v-if="lastSyncTime > 0" class="info-item">
          <span>更新：{{ formatSyncTime(lastSyncTime) }}</span>
        </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="0">低</option>
        <option :value="1">中</option>
        <option :value="2">高</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 v-if="filteredTasks.length === 0" class="empty">暂无任务</div>

    <div v-else class="tasks-shell">
      <div class="tasks-scroll">
        <TaskItem
          v-for="task in filteredTasks"
          :key="task.id"
          :task="task"
          @updated="handleTaskUpdated"
          @deleted="handleTaskDeleted"
          @subtask-created="handleSubTaskCreated"
        />
      </div>
    </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<0 | 1 | 2>(1);
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 toggleSortOrder = () => {
  sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc';
};

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 filteredTasks = computed(() => {
  const rootTasks = tasks.value.filter(t => !t.parentTaskId);
  
  if (showCompleted.value) {
    // 当显示已完成时，返回所有根任务（不进行过滤，保持原始树结构）
    return sortTasks(rootTasks);
  } else {
    // 当隐藏已完成时，递归过滤掉已完成的任务
    const activeTasks = filterTasksByCompletion(rootTasks, false);
    return sortTasks(activeTasks);
  }
});

const sortTasks = (tasks: Task[]): Task[] => {
  const priorityOrder: Record<number, number> = {
    2: 3,
    1: 2,
    0: 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 aVal = a.isCompleted ? new Date(a.updatedAt).getTime() : 0;
        const bVal = b.isCompleted ? new Date(b.updatedAt).getTime() : 0;
        comparison = bVal - aVal;
        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;
  });

  return sorted.map(task => {
    if (task.subTasks && task.subTasks.length > 0) {
      return {
        ...task,
        subTasks: sortTasks(task.subTasks)
      };
    }
    return task;
  });
};

const filterTasksByCompletion = (tasks: Task[], isCompleted: boolean): Task[] => {
  return tasks
    .map(task => ({ ...task })) // 创建任务的浅拷贝，避免修改原始数据
    .filter(task => {
      // 如果任务本身符合完成状态，保留它
      if (task.isCompleted === isCompleted) {
        // 如果任务本身符合状态，其子任务也需要递归过滤
        if (task.subTasks && task.subTasks.length > 0) {
          task.subTasks = filterTasksByCompletion(task.subTasks, 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 = 1;
    }
  } 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 {
  width: 100%;
  max-width: none;
  margin: 0;
  padding: 0;
  background: transparent;
  min-height: 100vh;
  height: 100dvh;
  display: flex;
  flex-direction: column;
}

.page-header {
  background: white;
  padding: 4px 6px;
  border-radius: 16px;
  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;
  gap: 8px;
  --header-chip-height: 24px;
  --header-chip-font-size: 10px;
  --header-chip-pad-x: 8px;
}

.header-controls {
  flex: 1;
  min-width: 0;
}

    .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: none;
        border-bottom: 2px solid #e2e8f0;
        border-radius: 0;
        font-size: 14px;
        transition: all 0.3s ease;
        background: transparent;
        color: #1e293b;
    }

        .task-input:focus {
            outline: none;
            border-bottom-color: #6366f1;
            background: transparent;
            box-shadow: none;
        }

    .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);
}

.task-select option {
  background: white;
  color: #1e293b;
}

.task-select option[value="0"] {
  color: #22c55e;
}

.task-select option[value="1"] {
  color: #f59e0b;
}

.task-select option[value="2"] {
  color: #ef4444;
}

.btn-add {
    padding: 8px 16px;
    background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 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(37, 99, 235, 0.4);
    display: flex;
    align-items: center;
    justify-content: center;
}

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

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

.checkbox-wrapper {
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  user-select: none;
  height: var(--header-chip-height);
  padding: 0 var(--header-chip-pad-x);
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
}

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

.checkbox-input {
  width: 14px;
  height: 14px;
  cursor: pointer;
  -webkit-appearance: none;
  appearance: none;
  border: 1.5px solid rgba(100, 116, 139, 0.6);
  border-radius: 4px;
  background: rgba(255, 255, 255, 0.92);
  display: grid;
  place-content: center;
  transition: background-color 0.2s ease, border-color 0.2s ease, box-shadow 0.2s ease;
}

.checkbox-input::after {
  content: '';
  width: 5px;
  height: 8px;
  border-right: 2px solid #ffffff;
  border-bottom: 2px solid #ffffff;
  transform: translateY(-1px) rotate(45deg);
  opacity: 0;
  transition: opacity 0.2s ease;
}

.checkbox-input:checked {
  background: #6366f1;
  border-color: #6366f1;
}

.checkbox-input:checked::after {
  opacity: 1;
}

.checkbox-input:focus-visible {
  outline: 2px solid rgba(99, 102, 241, 0.55);
  outline-offset: 2px;
}

@media (prefers-color-scheme: dark) {
  .checkbox-input {
    border-color: rgba(148, 163, 184, 0.75);
    background: rgba(15, 23, 42, 0.35);
  }
}

.checkbox-label {
  font-size: var(--header-chip-font-size);
  font-weight: 400;
  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;
  flex-shrink: 0;
}

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

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

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

.sort-select {
  height: var(--header-chip-height);
  padding: 0 calc(var(--header-chip-pad-x) + 14px) 0 var(--header-chip-pad-x);
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  cursor: pointer;
  font-size: var(--header-chip-font-size);
  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;
}

.sort-select.sort-order-btn {
  height: var(--header-chip-height);
  width: var(--header-chip-height);
  padding: 0;
  min-width: 0;
  border-radius: 8px;
  font-size: 0;
  line-height: 0;
  box-sizing: border-box;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  user-select: none;
}

.sort-order-icon {
  width: 14px;
  height: 14px;
  display: block;
  flex-shrink: 0;
}

.sort-order-btn:active {
  transform: translateY(0.5px);
}

.hotkey-settings-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  height: var(--header-chip-height);
  padding: 0 var(--header-chip-pad-x);
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: var(--header-chip-font-size);
  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 {
  width: 14px;
  height: 14px;
  flex-shrink: 0;
}

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

.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-shell {
  display: flex;
  flex: 1;
  min-height: 0;
  background: rgba(255, 255, 255, 0.85);
  border: 1px solid #e2e8f0;
  border-radius: 18px;
  padding: 10px;
}

.tasks-scroll {
  display: flex;
  flex: 1;
  min-height: 0;
  flex-direction: column;
  gap: 10px;
  overflow-y: auto;
  scrollbar-gutter: stable;
}

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

  .page-header {
    padding: 4px 6px;
    border-radius: 14px;
    margin-bottom: 8px;
    flex-direction: row;
    flex-wrap: wrap;
    align-items: center;
    gap: 6px;
  }

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

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

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

  .btn-add {
    padding: 8px 14px;
    font-size: 14px;
    border-radius: 12px;
  }

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

  .checkbox-wrapper {
    height: var(--header-chip-height);
    padding: 0 var(--header-chip-pad-x);
  }

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

  .checkbox-label {
    font-size: var(--header-chip-font-size);
  }

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

  .sort-select {
    height: var(--header-chip-height);
    padding: 0 calc(var(--header-chip-pad-x) + 14px) 0 var(--header-chip-pad-x);
    font-size: var(--header-chip-font-size);
    flex: none;
  }

  .hotkey-settings-btn {
    height: var(--header-chip-height);
    padding: 0 var(--header-chip-pad-x);
    font-size: var(--header-chip-font-size);
    border-radius: 8px;
  }

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

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

  .info-item {
    height: var(--header-chip-height);
    padding: 0 var(--header-chip-pad-x);
    font-size: var(--header-chip-font-size);
  }

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

  .tasks {
    gap: 6px;
  }
}

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

  .page-header {
    padding: 4px 6px;
    border-radius: 14px;
    margin-bottom: 6px;
  }

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

  .title-icon {
    width: 22px;
    height: 22px;
    padding: 3px;
  }

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

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

  .task-select {
    padding: 6px 8px;
    font-size: 14px;
    min-width: 72px;
    border-radius: 10px;
  }

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

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

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

  .checkbox-wrapper {
    height: var(--header-chip-height);
    padding: 0 var(--header-chip-pad-x);
  }

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

  .checkbox-label {
    font-size: var(--header-chip-font-size);
  }

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

  .sort-select {
    height: var(--header-chip-height);
    padding: 0 calc(var(--header-chip-pad-x) + 14px) 0 var(--header-chip-pad-x);
    font-size: var(--header-chip-font-size);
    flex: none;
  }

  .hotkey-settings-btn {
    height: var(--header-chip-height);
    padding: 0 var(--header-chip-pad-x);
    font-size: var(--header-chip-font-size);
    border-radius: 8px;
  }

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

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

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

  .info-item {
    height: var(--header-chip-height);
    padding: 0 var(--header-chip-pad-x);
    font-size: var(--header-chip-font-size);
  }

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

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

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