<template>
  <div class="tasks">
    <header class="page-header">
      <h1>{{ $t('tasks.title') }}</h1>
      <div class="header-actions">
        <button class="btn btn-ghost" @click="refresh">{{ $t('tasks.refresh') }}</button>
        <button class="btn btn-primary" @click="openCreateModal">{{ $t('tasks.create') }}</button>
      </div>
    </header>

    <!-- 筛选栏 -->
    <div class="filter-bar">
      <div class="filter-group">
        <span class="filter-label">{{ $t('tasks.filter.project') }}</span>
        <button
          v-for="p in projectFilters"
          :key="p.key"
          class="filter-btn"
          :class="{ active: activeProject === p.key }"
          @click="activeProject = p.key"
        >
          {{ p.label }}
        </button>
      </div>
      <div class="filter-group">
        <span class="filter-label">{{ $t('tasks.filter.status') }}</span>
        <button
          v-for="s in statusFilters"
          :key="s.key"
          class="filter-btn"
          :class="{ active: activeStatus === s.key }"
          @click="activeStatus = s.key"
        >
          {{ s.icon }} {{ s.label }}
        </button>
      </div>
    </div>

    <!-- 按项目分组 -->
    <div class="task-groups">
      <!-- Y-2: loading/error/empty 兜底(参考 Projects.vue 空态写法) -->
      <div v-if="loading" class="empty-state">{{ $t('common.loading') }}</div>
      <div v-else-if="store.error" class="empty-state">{{ store.error }}</div>
      <div v-else-if="filteredGroups.length === 0" class="empty-state">暂无任务</div>
      <template v-else>
        <section
          v-for="group in filteredGroups"
          :key="group.projectName"
          class="task-group"
        >
          <div class="group-header">
            <span class="group-icon">{{ group.icon }}</span>
            <h2 class="group-name">{{ group.projectName }}</h2>
            <span class="group-count">{{ $t('tasks.group.taskCount', { n: group.tasks.length }) }}</span>
          </div>
          <div class="task-list">
            <div class="task-item" v-for="task in group.tasks" :key="task.id" @click="router.push(`/tasks/${task.id}`)">
              <div class="task-main">
                <div class="task-title-row">
                  <span class="task-title">{{ task.title }}</span>
                  <span class="priority-badge" :class="priorityClass(task.priority)">{{ priorityLabel(task.priority) }}</span>
                </div>
                <div class="task-meta">
                  <span class="branch-tag" v-if="task.branch_name">
                    <span class="branch-icon">⑂</span>
                    {{ task.branch_name }}
                  </span>
                  <span class="task-date">{{ formatRelativeZh(task.created_at) }}</span>
                  <span class="task-time">{{ formatRelativeZh(task.updated_at) }}</span>
                </div>
              </div>
              <span class="status-tag" :class="taskStatusClass(task.status)">{{ $t(statusLabel(task.status)) }}</span>
            </div>
          </div>
        </section>
      </template>
    </div>

    <!-- 新建任务模态框 -->
    <div class="modal-overlay" v-if="showCreateModal" @click.self="showCreateModal = false">
      <div class="modal-box">
        <h3>{{ $t('tasks.modal.title') }}</h3>
        <label style="font-size:12px;color:var(--df-text-secondary);margin-bottom:4px;display:block">{{ $t('tasks.modal.project') }}</label>
        <select v-model="newTaskProjectId" style="width:100%;padding:8px 12px;border: 0.5px solid var(--df-border);border-radius: var(--df-radius-sm);background:var(--df-bg);color:var(--df-text);font-size:13px;margin-bottom:12px">
          <option v-for="p in store.projects" :key="p.id" :value="p.id">{{ p.name }}</option>
        </select>
        <label style="font-size:12px;color:var(--df-text-secondary);margin-bottom:4px;display:block">{{ $t('tasks.modal.titleField') }}</label>
        <input v-model="newTaskTitle" :placeholder="$t('tasks.modal.titlePlaceholder')" @keyup.enter="confirmCreate" />
        <label style="font-size:12px;color:var(--df-text-secondary);margin-bottom:4px;display:block">{{ $t('tasks.modal.desc') }}</label>
        <input v-model="newTaskDesc" :placeholder="$t('tasks.modal.descPlaceholder')" style="width:100%;padding:8px 12px;border: 0.5px solid var(--df-border);border-radius: var(--df-radius-sm);background:var(--df-bg);color:var(--df-text);font-size:13px;margin-bottom:12px;box-sizing:border-box" />
        <label style="font-size:12px;color:var(--df-text-secondary);margin-bottom:4px;display:block">{{ $t('tasks.modal.branch') }}</label>
        <input v-model="newTaskBranch" :placeholder="$t('tasks.modal.branchPlaceholder')" style="width:100%;padding:8px 12px;border: 0.5px solid var(--df-border);border-radius: var(--df-radius-sm);background:var(--df-bg);color:var(--df-text);font-size:13px;margin-bottom:12px;box-sizing:border-box" />
        <label style="font-size:12px;color:var(--df-text-secondary);margin-bottom:4px;display:block">{{ $t('tasks.modal.priority') }}</label>
        <select v-model="newTaskPriority" style="width:100%;padding:8px 12px;border: 0.5px solid var(--df-border);border-radius: var(--df-radius-sm);background:var(--df-bg);color:var(--df-text);font-size:13px;margin-bottom:12px">
          <option :value="0">{{ $t('tasks.modal.priorityCritical') }}</option>
          <option :value="1">{{ $t('tasks.modal.priorityHigh') }}</option>
          <option :value="2">{{ $t('tasks.modal.priorityMedium') }}</option>
          <option :value="3">{{ $t('tasks.modal.priorityLow') }}</option>
        </select>
        <div class="modal-actions">
          <button class="btn-cancel" @click="showCreateModal = false">{{ $t('common.cancel') }}</button>
          <button class="btn-confirm" @click="confirmCreate">{{ $t('common.confirm') }}</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useProjectStore } from '../stores/project'
import { formatRelativeZh } from '../utils/time'
import { taskStatusLabel as statusLabel, taskStatusClass, priorityLabel, priorityClass } from '../constants/project'
import type { TaskRecord } from '../api/types'

const router = useRouter()
const store = useProjectStore()
const { t } = useI18n()

const activeProject = ref('all')
const activeStatus = ref('all')
// Y-2: 本视图加载态(loadTasks 不翻转全局 state.loading,故用局部 ref 精确反映任务加载)
const loading = ref(false)

// ── 新建任务模态框 ──
const showCreateModal = ref(false)
const newTaskProjectId = ref('')
const newTaskTitle = ref('')
const newTaskDesc = ref('')
const newTaskBranch = ref('')
const newTaskPriority = ref(2) // 默认 medium

interface TaskGroup {
  projectName: string
  icon: string
  tasks: TaskRecord[]
}

const projectFilters = computed(() => [
  { key: 'all', label: t('tasks.filter.all') },
  ...store.projects.map(p => ({ key: p.id, label: p.name })),
])

const statusFilters = computed<{ key: string; label: string; icon: string }[]>(() => [
  { key: 'all', label: t('tasks.statusFilter.all'), icon: '📋' },
  { key: 'todo', label: t('tasks.statusFilter.todo'), icon: '📝' },
  { key: 'in_progress', label: t('tasks.statusFilter.in_progress'), icon: '🔨' },
  { key: 'review_ready', label: t('tasks.statusFilter.review_ready'), icon: '👀' },
  { key: 'merged', label: t('tasks.statusFilter.merged'), icon: '✅' },
  { key: 'abandoned', label: t('tasks.statusFilter.abandoned'), icon: '🗑️' },
])

function getProjectName(projectId: string): string {
  return store.projects.find(p => p.id === projectId)?.name ?? t('tasks.group.unknownProject')
}

const projectIcons: Record<string, string> = {
  'u-ask': '🤖',
  'u-img': '🖼️',
  'flux': '⚡',
}

const filteredGroups = computed(() => {
  let filtered = store.tasks
  if (activeProject.value !== 'all') {
    filtered = filtered.filter(t => t.project_id === activeProject.value)
  }
  if (activeStatus.value !== 'all') {
    filtered = filtered.filter(t => t.status === activeStatus.value)
  }

  const groupMap = new Map<string, TaskRecord[]>()
  for (const task of filtered) {
    if (!groupMap.has(task.project_id)) {
      groupMap.set(task.project_id, [])
    }
    groupMap.get(task.project_id)!.push(task)
  }

  const result: TaskGroup[] = []
  for (const [projectId, groupTasks] of groupMap) {
    const name = getProjectName(projectId)
    result.push({
      projectName: name,
      icon: projectIcons[name] || '📂',
      tasks: groupTasks,
    })
  }
  return result
})

// statusLabel / priorityLabel / priorityClass 由 ../constants/project 提供(与 ProjectDetail 文案统一)

async function refresh() {
  loading.value = true
  try {
    await store.loadTasks(activeProject.value === 'all' ? undefined : activeProject.value)
  } finally {
    loading.value = false
  }
}

function openCreateModal() {
  newTaskProjectId.value = store.projects.length > 0 ? store.projects[0].id : ''
  newTaskTitle.value = ''
  newTaskDesc.value = ''
  newTaskBranch.value = ''
  newTaskPriority.value = 2
  showCreateModal.value = true
}

async function confirmCreate() {
  if (!newTaskTitle.value.trim() || !newTaskProjectId.value) return
  const r = await store.createTask({
    project_id: newTaskProjectId.value,
    title: newTaskTitle.value.trim(),
    description: newTaskDesc.value.trim(),
    branch_name: newTaskBranch.value.trim() || undefined,
    priority: newTaskPriority.value,
  })
  if (!r) return // 失败已 toast,保持弹窗不关
  showCreateModal.value = false
}

// B-260615-29: 切换项目筛选时按 projectId 重载(避免仅前端 filter,跨项目视图不同步)
// CR-260615-26(R-1): 同步登记当前筛选到 store,供 AR-11 listener 按筛选拉取
watch(activeProject, (key) => {
  store.setActiveTaskProject(key)
  loading.value = true
  store.loadTasks(key === 'all' ? undefined : key).finally(() => { loading.value = false })
})

onMounted(async () => {
  // R-1: 登记初始筛选(all=全量),让数据变更 listener 知道视图已挂载、按全量拉取
  store.setActiveTaskProject(activeProject.value)
  loading.value = true
  try {
    await Promise.all([store.loadProjects(), store.loadTasks()])
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>
.tasks { padding: 16px 20px 20px; }

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--df-gap-page);
}
.page-header h1 { font-size: 24px; font-weight: 500; color: var(--df-text); }
.header-actions { display: flex; gap: 10px; }

/* ===== 按钮 ===== */
.btn {
  padding: 8px 16px;
  border: none;
  border-radius: var(--df-radius-sm);
  font-size: 13px;
  cursor: pointer;
  transition: all 0.15s;
}
.btn-primary { background: var(--df-accent); color: #fff; }
.btn-primary:hover { background: var(--df-accent-hover); }
.btn-ghost { background: transparent; color: var(--df-text-secondary); border: 0.5px solid var(--df-border); }
.btn-ghost:hover { background: var(--df-bg-card); color: var(--df-text); }

/* ===== 筛选栏 ===== */
.filter-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: var(--df-gap-page);
  padding: var(--df-pad-panel);
  background: var(--df-bg-card);
  border: 0.5px solid var(--df-border);
  border-radius: var(--df-radius-lg);
}
.filter-group {
  display: flex;
  align-items: center;
  gap: 6px;
}
.filter-label {
  font-size: 12px;
  color: var(--df-text-dim);
  white-space: nowrap;
}
.filter-btn {
  padding: 4px 12px;
  border: 0.5px solid var(--df-border);
  border-radius: var(--df-radius-sm);
  background: transparent;
  color: var(--df-text-secondary);
  font-size: 12px;
  cursor: pointer;
  transition: all 0.15s;
}
.filter-btn:hover { background: rgba(108, 99, 255, 0.06); color: var(--df-text); }
.filter-btn.active {
  background: var(--df-accent);
  color: #fff;
  border-color: var(--df-accent);
}

/* ===== 任务分组 ===== */
.task-groups {
  display: flex;
  flex-direction: column;
  gap: var(--df-gap-grid);
}

.task-group {
  background: var(--df-bg-card);
  border: 0.5px solid var(--df-border);
  border-radius: var(--df-radius-lg);
  padding: var(--df-pad-panel);
}

.group-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: var(--df-gap-head);
  padding-bottom: 10px;
  border-bottom: 0.5px solid var(--df-border);
}
.group-icon { font-size: 18px; }
.group-name { font-size: 15px; font-weight: 500; color: var(--df-text); }
.group-count { font-size: 12px; color: var(--df-text-dim); margin-left: 8px; }

/* ===== 任务条目 ===== */
.task-list {
  display: flex;
  flex-direction: column;
}
.task-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 14px;
  border-radius: var(--df-radius);
  transition: background 0.1s;
  cursor: pointer;
}
.task-item:hover { background: rgba(108, 99, 255, 0.04); }

.task-main { flex: 1; min-width: 0; }

.task-title-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}
.task-title { font-size: 14px; font-weight: 500; color: var(--df-text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

.priority-badge {
  font-size: 10px; font-weight: 500;
  padding: 1px 6px;
  border-radius: var(--df-radius-xs);
}
.priority-critical { background: rgba(255,107,107,0.2); color: var(--df-danger); }
.priority-high { background: rgba(255,152,0,0.2); color: #ff9800; }
.priority-medium { background: rgba(100,181,246,0.2); color: var(--df-info); }
.priority-low { background: rgba(90,99,128,0.2); color: var(--df-text-dim); }

.task-meta {
  display: flex;
  align-items: center;
  gap: 14px;
}
.branch-tag {
  display: inline-flex;
  align-items: center;
  gap: 3px;
  font-size: 12px;
  color: var(--df-text-secondary);
  background: rgba(108, 99, 255, 0.06);
  padding: 2px 8px;
  border-radius: var(--df-radius-xs);
  font-family: monospace;
}
.branch-icon { font-size: 12px; color: var(--df-accent); }
.task-date { font-size: 11px; color: var(--df-text-dim); }
.task-time {
  font-size: 11px;
  color: var(--df-text-dim);
  opacity: 0.7;
}

/* ===== 状态标签 ===== */
.status-tag {
  font-size: 11px; font-weight: 500;
  padding: 4px 10px;
  border-radius: var(--df-radius-sm);
  white-space: nowrap;
}
.status-todo { background: rgba(90,99,128,0.2); color: var(--df-text-dim); }
.status-progress { background: rgba(100,181,246,0.2); color: var(--df-info); }
.status-review { background: rgba(255,217,61,0.2); color: var(--df-warning); }
.status-done { background: rgba(100,255,218,0.15); color: var(--df-success); }
.status-abandoned { background: rgba(255,107,107,0.2); color: var(--df-danger); }

/* ===== 空状态(Y-2: loading/error/empty 兜底,样式参考 Projects.vue) ===== */
.empty-state {
  text-align: center; padding: 60px 20px;
  font-size: 14px; color: var(--df-text-dim);
}

/* ===== 模态框 ===== */
.modal-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 100; }
.modal-box { background: var(--df-bg-card); border: 0.5px solid var(--df-border); border-radius: var(--df-radius-lg); padding: 24px; min-width: 360px; max-width: 90vw; }
.modal-box h3 { color: var(--df-text); margin-bottom: 16px; }
.modal-box input, .modal-box select { width: 100%; padding: 8px 12px; border: 0.5px solid var(--df-border); border-radius: var(--df-radius-sm); background: var(--df-bg); color: var(--df-text); font-size: 13px; margin-bottom: 12px; box-sizing: border-box; }
.modal-box .modal-actions { display: flex; gap: 8px; justify-content: flex-end; }
.modal-box .btn-cancel { padding: 6px 16px; border: 0.5px solid var(--df-border); border-radius: var(--df-radius-sm); background: transparent; color: var(--df-text-secondary); cursor: pointer; }
.modal-box .btn-confirm { padding: 6px 16px; border: none; border-radius: var(--df-radius-sm); background: var(--df-accent); color: #fff; cursor: pointer; }
</style>
