<template>
  <div class="task-item" :class="{ completed: task.isCompleted, 'priority-low': task.priority === 0, 'priority-medium': task.priority === 1, 'priority-high': task.priority === 2 }">
    <div class="task-content" @dblclick="openEditDialog">
      <input
        type="checkbox"
        :checked="task.isCompleted"
        @change="toggleComplete"
        class="task-checkbox"
      />
      <button v-if="task.subTasks && task.subTasks.length > 0" class="task-expand" @click.stop="toggleExpand" :title="isExpanded ? '收起' : '展开'">
        <span class="expand-icon">{{ isExpanded ? '▼' : '▶' }}</span>
      </button>
      <button @click="startAddSubTask" 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 class="task-meta">
          <span class="task-id task-id--compact">#{{ task.id }}</span>
          <span class="task-priority task-priority--compact">{{ priorityShortText }}</span>
          <span class="task-created">创建{{ createdAtText }}</span>
        </div>
      </div>
      <div class="task-actions">
        <button @click="openEditDialog" class="btn-edit-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="M12 20h9" />
            <path stroke-linecap="round" stroke-linejoin="round" d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5Z" />
          </svg>
        </button>
        <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
        ref="subTaskInput"
        v-model="newSubTaskTitle"
        type="text"
        placeholder="输入子任务标题..."
        @keyup.enter="createSubTask"
        class="subtask-input"
      />
      <select v-model="newSubTaskPriority" class="subtask-select">
        <option :value="0">低</option>
        <option :value="1">中</option>
        <option :value="2">高</option>
      </select>
      <button @click="createSubTask" class="btn-create-subtask" title="创建子任务">
        <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>
      <button @click="showAddSubTask = false" class="btn-cancel" title="取消">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M18 6L6 18M6 6l12 12"></path>
        </svg>
      </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 { computed, ref, nextTick } 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<0 | 1 | 2>(1);
const subTaskInput = ref<HTMLInputElement | null>(null);

const startAddSubTask = async () => {
  showAddSubTask.value = true;
  await nextTick();
  if (subTaskInput.value) {
    subTaskInput.value.focus();
  }
};

const priorityText = computed(() => {
  switch (props.task.priority) {
    case 0:
      return '低';
    case 2:
      return '高';
    case 1:
    default:
      return '中';
  }
});

const priorityShortText = computed(() => priorityText.value);

const formatDateTime = (value: string): string => {
  const date = new Date(value);
  if (!Number.isFinite(date.getTime())) return '';

  const pad2 = (n: number) => String(n).padStart(2, '0');
  const y = date.getFullYear();
  const m = pad2(date.getMonth() + 1);
  const d = pad2(date.getDate());
  const hh = pad2(date.getHours());
  const mm = pad2(date.getMinutes());
  const ss = pad2(date.getSeconds());
  return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
};

const createdAtText = computed(() => formatDateTime(props.task.createdAt));

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

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

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 = 1;
      }
  } catch (error) {
    console.error('Failed to create subtask:', error);
  }
};

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: 10px 12px;
  background: white;
  border: 1px solid rgba(226, 232, 240, 0.9);
  border-left-width: 8px;
  border-radius: 12px;
  margin-bottom: 0;
  transition: background 0.2s, box-shadow 0.2s, transform 0.2s, border-color 0.2s;
  user-select: none;
  -webkit-tap-highlight-color: transparent;
  text-align: left;
}

.task-item.priority-low {
  background: rgba(209, 250, 229, 0.65);
  border-color: rgba(167, 243, 208, 0.75);
  border-left-color: rgba(34, 197, 94, 0.9);
}

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

.task-item.priority-high {
  background: rgba(254, 226, 226, 0.7);
  border-color: rgba(254, 202, 202, 0.85);
  border-left-color: rgba(239, 68, 68, 0.9);
}

.task-item.priority-low:hover {
  background: rgba(209, 250, 229, 0.85);
}

.task-item.priority-medium:hover {
  background: rgba(254, 243, 199, 0.85);
}

.task-item.priority-high:hover {
  background: rgba(254, 226, 226, 0.85);
}

.task-item:hover {
  box-shadow: 0 10px 20px -12px rgba(15, 23, 42, 0.25);
}

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

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

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

.task-content:hover {
  background: transparent;
}

.task-expand {
  cursor: pointer;
  width: 18px;
  height: 18px;
  padding: 0;
  background: transparent;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

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

.task-checkbox {
  width: 18px;
  height: 18px;
  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;
}

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

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

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

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

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

.task-info {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 4px;
  flex: 1;
  min-width: 0;
}

.task-title {
  font-size: 15px;
  color: #374151;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
}

.task-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 0;
  width: 100%;
}

.task-created {
  font-size: 12px;
  line-height: 1.2;
  color: rgba(71, 85, 105, 0.85);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
}

.task-id {
  flex-shrink: 0;
  font-size: 12px;
  font-weight: 600;
  line-height: 1.2;
  padding: 2px 8px;
  border-radius: 999px;
  background: rgba(148, 163, 184, 0.14);
  color: rgba(71, 85, 105, 0.9);
  font-variant-numeric: tabular-nums;
}

.task-id--compact {
  font-size: 11px;
  padding: 1px 6px;
}

.task-priority {
  flex-shrink: 0;
  font-size: 12px;
  font-weight: 600;
  line-height: 1.2;
  padding: 2px 8px;
  border-radius: 999px;
  background: rgba(148, 163, 184, 0.18);
  color: rgba(71, 85, 105, 0.9);
}

.task-priority--compact {
  font-size: 11px;
  padding: 1px 6px;
}

.task-item.priority-low .task-priority {
  background: rgba(34, 197, 94, 0.14);
  color: rgba(21, 128, 61, 0.95);
}

.task-item.priority-medium .task-priority {
  background: rgba(245, 158, 11, 0.16);
  color: rgba(180, 83, 9, 0.95);
}

.task-item.priority-high .task-priority {
  background: rgba(239, 68, 68, 0.14);
  color: rgba(185, 28, 28, 0.95);
}

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

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

.btn-edit-icon:hover {
  background: #dbeafe;
  color: #1d4ed8;
}

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

.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;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
  justify-content: flex-end;
  margin-top: 10px;
  padding: 8px 12px;
  background: rgba(255, 255, 255, 0.55);
  border-radius: 12px;
  border: 1px solid rgba(0, 0, 0, 0.05);
  animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.subtask-input {
  width: 100%;
  padding: 8px;
  border: none;
  border-bottom: 1.5px solid rgba(0, 0, 0, 0.08);
  border-radius: 0;
  font-size: 14px;
  transition: all 0.3s ease;
  background: transparent;
  color: #1e293b;
}

.subtask-input::placeholder {
  color: #94a3b8;
}

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

.subtask-select {
  padding: 4px 8px;
  border: 1.5px solid rgba(0, 0, 0, 0.08);
  border-radius: 8px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.6);
  min-width: 60px;
  color: #1e293b;
}

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

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

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

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

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

.btn-create-subtask {
  padding: 4px 12px;
  background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px -2px rgba(37, 99, 235, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
}

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

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

.btn-cancel {
  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-cancel:hover {
  background: #fee2e2;
  color: #991b1b;
}

.btn-cancel:hover {
  background: #e2e8f0;
  color: #475569;
}

.add-subtask-form > * {
  box-sizing: border-box;
}

@media (max-width: 600px) {
  .add-subtask-form {
    flex-wrap: wrap;
    border-radius: 16px;
  }
  
  .subtask-input {
    flex: 1 1 100%;
    margin-bottom: 4px;
  }
}

.subtasks {
  margin-top: 10px;
  margin-left: 14px;
  padding: 0;
  border: none;
  background: transparent;
  border-radius: 0;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.subtasks :deep(.task-item) {
  border-left-width: 5px;
  padding: 10px 12px;
  box-shadow: none;
}

.subtasks :deep(.task-item:hover) {
  box-shadow: none;
}

.subtasks :deep(.task-item) {
  border-top-width: 0;
  border-right-width: 0;
  border-bottom-width: 0;
}

.subtasks :deep(.task-item.priority-low),
.subtasks :deep(.task-item.priority-medium),
.subtasks :deep(.task-item.priority-high) {
  border-top-color: transparent;
  border-right-color: transparent;
  border-bottom-color: transparent;
}

.task-item ::selection {
  background: transparent;
}
</style>
