<template>
  <div class="project-detail">
    <!-- 页面头部 -->
    <header class="page-header">
      <div class="header-left">
        <router-link to="/projects" class="back-link">← 项目列表</router-link>
        <h1>{{ currentProject?.name ?? '...' }}</h1>
        <span class="stage-badge" :class="'stage-' + stageKey">{{ statusLabel }}</span>
      </div>
      <div class="header-actions">
        <button class="btn btn-ghost" @click="handleSync">🔄 同步</button>
        <button class="btn btn-primary" @click="showNewTaskModal = true">+ 新任务</button>
      </div>
    </header>

    <!-- 新建任务模态框 -->
    <div v-if="showNewTaskModal" class="modal-overlay" @click.self="showNewTaskModal = false">
      <div class="modal-box">
        <h3 class="modal-title">新建任务</h3>
        <div class="modal-field">
          <label>任务标题</label>
          <input v-model="newTaskTitle" placeholder="输入任务标题" @keyup.enter="submitNewTask" />
        </div>
        <div class="modal-field">
          <label>描述</label>
          <textarea v-model="newTaskDesc" placeholder="简要描述" rows="3"></textarea>
        </div>
        <div class="modal-field">
          <label>分支名称</label>
          <input v-model="newTaskBranch" placeholder="feature/xxx" />
        </div>
        <div class="modal-actions">
          <button class="btn btn-ghost" @click="showNewTaskModal = false">取消</button>
          <button class="btn btn-primary" @click="submitNewTask" :disabled="!newTaskTitle.trim()">确认创建</button>
        </div>
      </div>
    </div>

    <!-- 阶段进度条 -->
    <div class="stage-pipeline">
      <div
        v-for="(stage, idx) in stages"
        :key="stage.key"
        class="stage-step"
        :class="{
          'stage-active': idx === currentStageIndex,
          'stage-done': idx < currentStageIndex,
        }"
      >
        <div class="stage-dot">
          <span v-if="idx < currentStageIndex">✓</span>
          <span v-else>{{ idx + 1 }}</span>
        </div>
        <div class="stage-label">{{ stage.label }}</div>
        <div v-if="idx < stages.length - 1" class="stage-connector" :class="{ 'connector-done': idx < currentStageIndex }"></div>
      </div>
    </div>

    <!-- 主体两栏 -->
    <div class="detail-grid">
      <!-- 左栏：项目信息 -->
      <section class="panel">
        <div class="panel-header">
          <h2>📋 项目信息</h2>
        </div>
        <div class="project-info" v-if="currentProject">
          <div class="info-item">
            <span class="label">来源想法</span>
            <router-link v-if="currentProject.idea_id" :to="`/ideas/${currentProject.idea_id}`" class="idea-link">
              查看想法详情
            </router-link>
            <span v-else class="no-idea">原始想法已删除</span>
          </div>
          <div class="info-item">
            <span class="label">创建时间</span>
            <span>{{ formatDate(currentProject.created_at) }}</span>
          </div>
          <div class="info-item">
            <span class="label">更新时间</span>
            <span>{{ formatDate(currentProject.updated_at) }}</span>
          </div>
          <div class="info-item">
            <span class="label">项目状态</span>
            <span class="status-badge" :class="currentProject.status">{{ currentProject.status }}</span>
          </div>
        </div>
      </section>

      <!-- 左栏：任务列表 -->
      <section class="panel">
        <div class="panel-header">
          <h2>🔀 任务列表</h2>
          <span class="task-count">{{ projectTasks.length }} 个任务</span>
        </div>
        <div class="task-list">
          <div class="task-card" v-for="task in projectTasks" :key="task.id">
            <div class="task-top">
              <span class="task-title">{{ task.title }}</span>
              <span class="task-status" :class="taskStatusClass(task.status)">{{ taskStatusLabel(task.status) }}</span>
            </div>
            <div class="task-branch" v-if="task.branch_name">
              <span class="branch-icon">⑂</span>
              <span class="branch-name">{{ task.branch_name }}</span>
            </div>
            <div class="task-meta">
              <span>{{ task.assignee ?? '—' }}</span>
              <span>{{ formatDate(task.created_at) }}</span>
              <span style="opacity: 0.7">{{ formatDate(task.updated_at) }}</span>
            </div>
          </div>
        </div>
        <div v-if="projectTasks.length === 0" class="empty-hint">暂无任务</div>
      </section>

      <!-- 右栏 -->
      <div class="right-column">
        <!-- 工作流执行日志 -->
        <section class="panel">
          <div class="panel-header">
            <h2>📋 工作流日志</h2>
            <button class="btn btn-ghost btn-sm" @click="runDemoWorkflow" :disabled="workflowRunning">▶ 运行测试工作流</button>
          </div>
          <div class="log-list" ref="logListRef">
            <div class="log-item" v-for="(evt, idx) in formattedEvents" :key="idx" :class="'log-' + evt.level">
              <span class="log-time">{{ evt.time }}</span>
              <span class="log-level">{{ evt.level }}</span>
              <span class="log-msg">{{ evt.message }}</span>
            </div>
            <div v-if="formattedEvents.length === 0" class="empty-hint">点击"运行测试工作流"查看实时日志</div>
          </div>
        </section>

        <!-- 项目上下文 -->
        <section class="panel">
          <div class="panel-header">
            <h2>🏷️ 项目信息</h2>
          </div>
          <div class="info-grid">
            <div class="info-row">
              <span class="info-label">状态</span>
              <span class="info-value">{{ statusLabel }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">描述</span>
              <span class="info-value">{{ currentProject?.description ?? '—' }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">来源想法</span>
              <span class="info-value">{{ currentProject?.idea_id ?? '—' }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">创建时间</span>
              <span class="info-value">{{ formatDate(currentProject?.created_at ?? '') }}</span>
            </div>
            <div class="info-row">
              <span class="info-label">更新时间</span>
              <span class="info-value">{{ formatDate(currentProject?.updated_at ?? '') }}</span>
            </div>
          </div>
        </section>
      </div>
    </div>

    <!-- 人工审批对话框 -->
    <div v-if="showApprovalDialog" class="modal-overlay">
      <div class="modal-box" style="width: 500px">
        <h3 class="modal-title">需要人工审批</h3>
        <div v-if="store.pendingApproval">
          <h3>{{ store.pendingApproval.title }}</h3>
          <p style="margin: 16px 0; color: var(--df-text-secondary);">{{ store.pendingApproval.description }}</p>
          <div style="margin-bottom: 20px;">
            <p style="margin-bottom: 8px; font-size: 14px;">请选择操作：</p>
            <div style="display: flex; gap: 12px; flex-wrap: wrap;">
              <button
                v-for="option in store.pendingApproval.options"
                :key="option"
                class="btn"
                :class="option === '同意' ? 'btn-primary' : 'btn-ghost'"
                @click="handleApproval(option)"
              >
                {{ option }}
              </button>
            </div>
          </div>
        </div>
        <div class="modal-actions">
          <button class="btn btn-ghost" @click="showApprovalDialog = false">稍后处理</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useProjectStore } from '../stores/project'
import { formatDate } from '../utils/time'
import type { WorkflowEventPayload } from '../api/types'

const route = useRoute()
const store = useProjectStore()
const logListRef = ref<HTMLElement | null>(null)
const showApprovalDialog = ref(false)
let unlisten: (() => void) | null = null

// ── 阶段定义 ──
const stages = [
  { key: 'idea', label: '💡 想法' },
  { key: 'requirement', label: '📋 需求' },
  { key: 'coding', label: '💻 编码' },
  { key: 'testing', label: '🧪 测试' },
  { key: 'release', label: '🚀 发布' },
]

// ── 状态映射 ──
const stageMap: Record<string, number> = {
  planning: 0, in_progress: 2, testing: 3, completed: 4, paused: 2, cancelled: 0,
}

const statusLabels: Record<string, string> = {
  planning: '📐 规划中',
  in_progress: '💻 进行中',
  paused: '⏸ 已暂停',
  completed: '✅ 已完成',
  cancelled: '❌ 已取消',
}

const taskStatusLabels: Record<string, string> = {
  todo: '📋 待开始',
  in_progress: '🔄 进行中',
  review_ready: '👀 待审查',
  merged: '✅ 已合并',
  abandoned: '❌ 已放弃',
}

const taskStatusClasses: Record<string, string> = {
  todo: 'status-todo',
  in_progress: 'status-progress',
  review_ready: 'status-review',
  merged: 'status-done',
  abandoned: 'status-todo',
}

// ── 当前项目 ──
const projectId = computed(() => route.params.id as string)
const currentProject = computed(() =>
  store.projects.find(p => p.id === projectId.value)
)
const stageKey = computed(() => currentProject.value?.status ?? 'planning')
const statusLabel = computed(() => statusLabels[stageKey.value] ?? stageKey.value)
const currentStageIndex = computed(() => stageMap[stageKey.value] ?? 0)

// ── 任务 ──
const projectTasks = computed(() =>
  store.tasks.filter(t => t.project_id === projectId.value)
)

function taskStatusLabel(status: string) {
  return taskStatusLabels[status] ?? status
}

function taskStatusClass(status: string) {
  return taskStatusClasses[status] ?? 'status-todo'
}

// ── 工作流 ──
const workflowRunning = ref(false)

const demoDag = {
  nodes: [
    { id: 'n1', node_type: 'script', label: '环境检查', config: { command: 'echo "Environment OK"', timeout_secs: 10 } },
    { id: 'n2', node_type: 'script', label: '运行测试', config: { command: 'echo "Tests passed"', timeout_secs: 10 } },
    { id: 'n3', node_type: 'script', label: '构建产物', config: { command: 'echo "Build success"', timeout_secs: 10 } },
  ],
  edges: [
    { from: 'n1', to: 'n2' },
    { from: 'n2', to: 'n3' },
  ],
}

async function runDemoWorkflow() {
  workflowRunning.value = true
  store.clearLiveEvents()
  try {
    await store.runWorkflow('demo-pipeline', demoDag)
  } finally {
    workflowRunning.value = false
  }
}

// ── 实时日志格式化 ──
interface LogEntry {
  time: string
  level: string
  message: string
}

const formattedEvents = computed<LogEntry[]>(() => {
  return store.liveEvents.map((evt: WorkflowEventPayload) => {
    const ev = evt.event
    const type = ev.type ?? 'unknown'
    const level = type.includes('error') || type.includes('fail') ? 'error'
      : type.includes('warn') ? 'warn' : 'info'
    const time = new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' })
    const message = ev.label
      ? `[${ev.label}] ${type}: ${ev.output ?? ev.code ?? ev.message ?? JSON.stringify(ev)}`
      : `${type}: ${ev.output ?? ev.code ?? ev.message ?? JSON.stringify(ev)}`
    return { time, level, message }
  })
})

// ── 新建任务 ──
const showNewTaskModal = ref(false)
const newTaskTitle = ref('')
const newTaskDesc = ref('')
const newTaskBranch = ref('')

async function submitNewTask() {
  if (!newTaskTitle.value.trim()) return
  await store.createTask({
    project_id: projectId.value,
    title: newTaskTitle.value.trim(),
    description: newTaskDesc.value.trim(),
    branch_name: newTaskBranch.value.trim() || undefined,
  })
  showNewTaskModal.value = false
  newTaskTitle.value = ''
  newTaskDesc.value = ''
  newTaskBranch.value = ''
}

// ── 同步 ──
async function handleSync() {
  await Promise.all([store.loadProjects(), store.loadTasks(projectId.value)])
}

// ── 审批处理 ──
async function handleApproval(decision: string) {
  await store.approveHumanApproval(decision)
  showApprovalDialog.value = false
}

// 监听审批请求
watch(() => store.pendingApproval, (newApproval) => {
  if (newApproval) {
    showApprovalDialog.value = true
  }
}, { immediate: true })

// ── 工具函数 ──
// formatDate 由 ../utils/time 提供（统一毫秒字符串解析，根治 Invalid Date）

// ── 生命周期 ──
onMounted(async () => {
  await store.loadProjects()
  await store.loadTasks(projectId.value)
  unlisten = (await store.startEventListener()) as any
})

onUnmounted(() => {
  if (unlisten) {
    unlisten()
    unlisten = null
  }
})
</script>

<style scoped>
/* ... 现有样式 ... */

/* ===== 项目信息样式 ===== */
.project-info {
  display: flex;
  flex-direction: column;
  gap: var(--df-gap-grid);
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-item .label {
  font-size: 12px;
  color: var(--df-text-dim);
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.info-item a.idea-link {
  color: var(--df-accent);
  text-decoration: none;
  font-weight: 500;
}

.info-item a.idea-link:hover {
  text-decoration: underline;
}

.info-item .no-idea {
  color: var(--df-text-dim);
  font-style: italic;
}

.status-badge {
  display: inline-block;
  padding: 2px 8px;
  border-radius: var(--df-radius-lg);
  font-size: 11px;
  font-weight: 500;
  background: rgba(108,99,255,0.1);
  color: var(--df-accent);
}
</style>

<style scoped>
.project-detail { padding: 16px 20px 20px; }

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--df-gap-page);
}
.header-left { display: flex; align-items: center; gap: 12px; }
.back-link { font-size: 13px; color: var(--df-accent); text-decoration: none; }
.back-link:hover { text-decoration: underline; }
.page-header h1 { font-size: 24px; font-weight: 500; color: var(--df-text); }

.stage-badge {
  font-size: 12px;
  padding: 3px 10px;
  border-radius: var(--df-radius-lg);
  font-weight: 500;
}
.stage-idea { background: rgba(100,181,246,0.15); color: var(--df-info); }
.stage-requirement { background: rgba(255,217,61,0.15); color: var(--df-warning); }
.stage-coding { background: rgba(108,99,255,0.15); color: var(--df-accent); }
.stage-testing { background: rgba(100,255,218,0.15); color: var(--df-success); }
.stage-release { background: rgba(255,107,107,0.15); color: #ff9800; }

.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); }
.btn-sm { padding: 4px 12px; font-size: 12px; }

/* ===== 阶段进度条 ===== */
.stage-pipeline {
  display: flex;
  align-items: flex-start;
  gap: 0;
  background: var(--df-bg-card);
  border: 0.5px solid var(--df-border);
  border-radius: var(--df-radius-lg);
  padding: var(--df-pad-panel);
  margin-bottom: var(--df-gap-page);
}
.stage-step {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  flex: 1;
}
.stage-dot {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 13px;
  font-weight: 500;
  background: var(--df-border);
  color: var(--df-text-dim);
  transition: all 0.2s;
  position: relative;
  z-index: 1;
}
.stage-active .stage-dot {
  background: var(--df-accent);
  color: #fff;
  
}
.stage-done .stage-dot {
  background: var(--df-success);
  color: var(--df-bg);
}
.stage-label {
  margin-top: 8px;
  font-size: 12px;
  color: var(--df-text-dim);
  white-space: nowrap;
}
.stage-active .stage-label { color: var(--df-accent); font-weight: 500; }
.stage-done .stage-label { color: var(--df-success); }

.stage-connector {
  position: absolute;
  top: 16px;
  left: calc(50% + 16px);
  width: calc(100% - 32px);
  height: 2px;
  background: var(--df-border);
}
.connector-done { background: var(--df-success); }

/* ===== 两栏布局 ===== */
.detail-grid {
  display: grid;
  grid-template-columns: 1fr 380px;
  gap: var(--df-gap-grid);
}
.right-column { display: flex; flex-direction: column; gap: var(--df-gap-grid); }

/* ===== 面板 ===== */
.panel {
  background: var(--df-bg-card);
  border: 0.5px solid var(--df-border);
  border-radius: var(--df-radius-lg);
  padding: var(--df-pad-panel);
}
.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--df-gap-head);
}
.panel-header h2 { font-size: 15px; font-weight: 500; }
.task-count { font-size: 12px; color: var(--df-text-dim); }

/* ===== 任务卡片 ===== */
.task-list { display: flex; flex-direction: column; }
.task-card {
  padding: 14px 0;
  border-bottom: 0.5px solid var(--df-border);
}
.task-card:last-child { border-bottom: none; }
.task-top { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; }
.task-title { font-size: 14px; font-weight: 500; color: var(--df-text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.task-status { font-size: 11px; padding: 2px 8px; border-radius: var(--df-radius-xs); }
.status-done { background: rgba(100,255,218,0.15); color: var(--df-success); }
.status-progress { background: rgba(108,99,255,0.15); color: var(--df-accent); }
.status-review { background: rgba(255,217,61,0.15); color: var(--df-warning); }
.status-todo { background: rgba(90,99,128,0.2); color: var(--df-text-dim); }

.task-branch {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-bottom: 6px;
}
.branch-icon { color: var(--df-accent); font-size: 13px; }
.branch-name {
  font-size: 12px;
  font-family: 'SF Mono', 'Fira Code', monospace;
  color: var(--df-text-secondary);
  background: rgba(108,99,255,0.1);
  padding: 1px 6px;
  border-radius: var(--df-radius-sm);
}
.task-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: var(--df-text-dim);
}

/* ===== 日志 ===== */
.log-list {
  font-family: 'SF Mono', 'Fira Code', monospace;
  font-size: 12px;
  max-height: 280px;
  overflow-y: auto;
}
.log-item {
  display: flex;
  gap: 8px;
  padding: 5px 0;
  border-bottom: 0.5px solid rgba(42,42,74,0.5);
}
.log-item:last-child { border-bottom: none; }
.log-time { color: var(--df-text-dim); min-width: 64px; }
.log-level {
  min-width: 42px;
  font-weight: 500;
  text-transform: uppercase;
  font-size: 10px;
  padding: 1px 4px;
  border-radius: var(--df-radius-sm);
  text-align: center;
}
.log-info .log-level { color: var(--df-info); }
.log-warn .log-level { color: var(--df-warning); }
.log-error .log-level { color: var(--df-danger); }
.log-msg { color: var(--df-text-secondary); flex: 1; }

/* ===== 项目信息 ===== */
.info-grid { display: flex; flex-direction: column; gap: 0; }
.info-row {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 0.5px solid var(--df-border);
}
.info-row:last-child { border-bottom: none; }
.info-label { font-size: 13px; color: var(--df-text-dim); }
.info-value { font-size: 13px; color: var(--df-text-secondary); font-weight: 500; }

/* ===== 模态框 ===== */
.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;
  width: 420px;
  max-width: 90vw;
}
.modal-title { font-size: 18px; font-weight: 500; color: var(--df-text); margin-bottom: 16px; }
.modal-field { margin-bottom: 14px; }
.modal-field label { display: block; font-size: 12px; color: var(--df-text-dim); margin-bottom: 4px; }
.modal-field input, .modal-field textarea {
  width: 100%; padding: 8px 10px; border-radius: var(--df-radius-sm);
  border: 0.5px solid var(--df-border); background: var(--df-bg);
  color: var(--df-text); font-size: 13px; font-family: inherit;
  box-sizing: border-box;
}
.modal-field input:focus, .modal-field textarea:focus {
  outline: none; border-color: var(--df-accent);
}
.modal-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 4px; }
.btn:disabled { opacity: 0.4; cursor: not-allowed; }

.empty-hint {
  text-align: center; padding: 24px 12px;
  font-size: 13px; color: var(--df-text-dim);
}

/* ===== 响应式 ===== */
@media (max-width: 900px) {
  .project-detail { padding: 16px; }
  .detail-grid {
    grid-template-columns: 1fr;
  }
  .stage-pipeline { overflow-x: auto; }
}
</style>
