<template>
  <div class="task-item" :class="{ completed: task.isCompleted, 'priority-low': task.priority === 'Low', 'priority-medium': task.priority === 'Medium', 'priority-high': task.priority === 'High' }">
    <div class="task-content" @dblclick="openEditDialog">
      <div class="task-expand" @click="toggleExpand" v-if="task.subTasks && task.subTasks.length > 0">
        <span class="expand-icon">{{ isExpanded ? '▼' : '▶' }}</span>
      </div>
      <div v-else class="task-expand-spacer"></div>
      <input
        type="checkbox"
        :checked="task.isCompleted"
        @change="toggleComplete"
        class="task-checkbox"
      />
      <button @click="showAddSubTask = true" class="btn-add-subtask-icon" title="添加子任务">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
          <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m3.75 9v6m3-3H9m1.5-12H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z" />
        </svg>
      </button>
      <div class="task-info">
        <span class="task-title">{{ task.title }}</span>
      </div>
      <div class="task-actions">
        <button @click="deleteTask" class="btn-delete-icon" title="删除">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>
    </div>
    
    <div v-if="showAddSubTask" class="add-subtask-form">
      <input
        v-model="newSubTaskTitle"
        type="text"
        placeholder="输入子任务标题..."
        @keyup.enter="createSubTask"
        class="subtask-input"
      />
      <select v-model="newSubTaskPriority" class="subtask-select">
        <option value="Low">低</option>
        <option value="Medium">中</option>
        <option value="High">高</option>
      </select>
      <button @click="createSubTask" class="btn-create-subtask">创建</button>
      <button @click="showAddSubTask = false" class="btn-cancel">取消</button>
    </div>

    <div v-if="isExpanded && task.subTasks && task.subTasks.length > 0" class="subtasks">
      <TaskItem
        v-for="subTask in task.subTasks"
        :key="subTask.id"
        :task="subTask"
        @updated="handleSubTaskUpdated"
        @deleted="handleSubTaskDeleted"
        @subtask-created="$emit('subtask-created', $event)"
      />
    </div>

    <TaskEditDialog
      v-model:visible="showEditDialog"
      :task="task"
      @saved="handleTaskSaved"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { taskApi } from '../api/tasks';
import TaskEditDialog from './TaskEditDialog.vue';
import type { Task } from '../types/task';

interface Props {
  task: Task;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  (e: 'updated', task: Task): void;
  (e: 'deleted', id: number): void;
  (e: 'subtask-created', task: Task): void;
}>();

const isExpanded = ref(false);
const showAddSubTask = ref(false);
const showEditDialog = ref(false);
const newSubTaskTitle = ref('');
const newSubTaskPriority = ref<'Low' | 'Medium' | 'High'>('Medium');

const toggleExpand = () => {
  isExpanded.value = !isExpanded.value;
};

const toggleComplete = async () => {
  try {
    const response = await taskApi.toggleComplete(props.task.id);
    if (response.success && response.data) {
      emit('updated', response.data);
    }
  } catch (error) {
    console.error('Failed to toggle task:', error);
    alert('切换任务状态失败');
  }
};

const deleteTask = async () => {
  try {
    const response = await taskApi.deleteTask(props.task.id);
    if (response.success) {
      emit('deleted', props.task.id);
    }
  } catch (error) {
    console.error('Failed to delete task:', error);
    alert('删除任务失败');
  }
};

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

  try {
    const response = await taskApi.createTask({
      title: newSubTaskTitle.value.trim(),
      priority: newSubTaskPriority.value,
      parentTaskId: props.task.id,
    });

    if (response.success && response.data) {
      emit('subtask-created', response.data);
      showAddSubTask.value = false;
      newSubTaskTitle.value = '';
      newSubTaskPriority.value = 'Medium';
    }
  } catch (error) {
    console.error('Failed to create subtask:', error);
    alert('创建子任务失败');
  }
};

const handleSubTaskUpdated = (updatedTask: Task) => {
  if (props.task.subTasks) {
    const index = props.task.subTasks.findIndex(t => t.id === updatedTask.id);
    if (index !== -1) {
      props.task.subTasks[index] = updatedTask;
      emit('updated', props.task);
    }
  }
};

const handleSubTaskDeleted = (subTaskId: number) => {
  if (props.task.subTasks) {
    props.task.subTasks = props.task.subTasks.filter(t => t.id !== subTaskId);
    emit('updated', props.task);
  }
};

const openEditDialog = () => {
  showEditDialog.value = true;
};

const handleTaskSaved = (updatedTask: Task) => {
  emit('updated', updatedTask);
};
</script>

<style scoped>
.task-item {
  display: flex;
  flex-direction: column;
  padding: 8px 12px;
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  margin-bottom: 6px;
  transition: all 0.2s;
}

.task-item.priority-low {
  background: rgba(209, 250, 229, 0.5);
  border-color: rgba(167, 243, 208, 0.6);
}

.task-item.priority-medium {
  background: rgba(254, 243, 199, 0.5);
  border-color: rgba(253, 230, 138, 0.6);
}

.task-item.priority-high {
  background: rgba(254, 226, 226, 0.5);
  border-color: rgba(254, 202, 202, 0.6);
}

.task-item.priority-low:hover {
  background: rgba(209, 250, 229, 0.7);
  border-color: rgba(167, 243, 208, 0.8);
}

.task-item.priority-medium:hover {
  background: rgba(254, 243, 199, 0.7);
  border-color: rgba(253, 230, 138, 0.8);
}

.task-item.priority-high:hover {
  background: rgba(254, 226, 226, 0.7);
  border-color: rgba(254, 202, 202, 0.8);
}

.task-item:hover {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.task-item.completed {
  opacity: 0.6;
}

.task-item.completed .task-title {
  text-decoration: line-through;
}

.task-content {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  cursor: pointer;
  user-select: none;
}

.task-content:hover {
  background: rgba(249, 250, 251, 0.5);
  border-radius: 4px;
}

.task-expand {
  cursor: pointer;
  width: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.expand-icon {
  font-size: 10px;
  color: #6b7280;
  transition: transform 0.2s;
}

.task-expand-spacer {
  width: 16px;
}

.task-checkbox {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

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

.task-title {
  font-size: 13px;
  color: #374151;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
}

.task-actions {
  display: flex;
  gap: 6px;
  flex-shrink: 0;
  align-items: center;
}

.btn-add-subtask {
  padding: 4px 10px;
  background: #dbeafe;
  color: #1e40af;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  font-size: 11px;
  transition: background 0.2s;
  display: flex;
  align-items: center;
  gap: 4px;
}

.btn-add-subtask svg {
  flex-shrink: 0;
}

.btn-add-subtask-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  padding: 0;
  background: transparent;
  color: #6b7280;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  flex-shrink: 0;
}

.btn-add-subtask-icon:hover {
  background: #dbeafe;
  color: #1e40af;
}

.btn-add-subtask-icon svg {
  flex-shrink: 0;
}

.btn-add-subtask:hover {
  background: #bfdbfe;
}

.btn-delete-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  padding: 0;
  background: transparent;
  color: #dc2626;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  flex-shrink: 0;
}

.btn-delete-icon:hover {
  background: #fee2e2;
  color: #991b1b;
}

.btn-delete-icon svg {
  flex-shrink: 0;
}

.add-subtask-form {
  display: flex;
  gap: 6px;
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid #e5e7eb;
}

.subtask-input {
  flex: 1;
  padding: 6px;
  border: 1px solid #d1d5db;
  border-radius: 5px;
  font-size: 11px;
}

.subtask-select {
  padding: 6px;
  border: 1px solid #d1d5db;
  border-radius: 5px;
  font-size: 11px;
  cursor: pointer;
}

.btn-create-subtask {
  padding: 6px 12px;
  background: #3b82f6;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 11px;
  transition: background 0.2s;
}

.btn-create-subtask:hover {
  background: #2563eb;
}

.btn-cancel {
  padding: 6px 12px;
  background: #e5e7eb;
  color: #374151;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 11px;
  transition: background 0.2s;
}

.btn-cancel:hover {
  background: #d1d5db;
}

.subtasks {
  margin-top: 8px;
  padding-left: 24px;
  border-left: 2px solid #e5e7eb;
}
</style>
