<template>
  <view class="page progress-page">
    <view class="progress-head panel">
      <view class="progress-head__top">
        <view class="progress-head__main">
          <text class="progress-head__label">{{ modeTitle }}</text>
          <text class="progress-head__title">{{ project?.name || project?.title || "视频项目" }}</text>
        </view>
        <text class="status-pill" :class="statusClass(run?.status)">{{ statusText(run?.status) }}</text>
      </view>
      <view class="progress-head__track">
        <view class="progress-head__fill" :style="{ width: `${percent}%` }" />
      </view>
      <view class="progress-head__percent">
        <text>制作进度</text>
        <text>{{ percent }}%</text>
      </view>
      <text class="progress-head__goal">{{ run?.goal || project?.description || "等待 Agent 返回任务目标" }}</text>
    </view>

    <view class="timeline-panel panel">
      <ProgressTimeline :steps="run?.steps" :mode="runMode" />
    </view>

    <view class="actions">
      <button v-if="run?.status === 'RUNNING'" class="secondary-button" @tap="pause">暂停</button>
      <button v-else-if="run?.status === 'PAUSED'" class="secondary-button" @tap="resume">继续</button>
      <button class="primary-button" :class="{ disabled: run?.status !== 'DONE' }" @tap="goResult">{{ resultButtonText }}</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed, onUnmounted, ref } from "vue";
import { onLoad, onPullDownRefresh } from "@dcloudio/uni-app";
import ProgressTimeline from "@/components/ProgressTimeline.vue";
import { getLatestRun, pauseRun, resumeRun } from "@/api/agent";
import { getProject } from "@/api/projects";
import type { AgentRun, ProjectDetail } from "@/types/api";
import type { RunModeValue } from "@/utils/constants";
import { statusClass, statusText, stepProgress } from "@/utils/format";

const projectId = ref<string | number>("");
const project = ref<ProjectDetail | null>(null);
const run = ref<AgentRun | null>(null);
let timer: ReturnType<typeof setInterval> | undefined;

const projectMetadata = computed(() => (project.value?.metadata || {}) as { runMode?: RunModeValue; runModeTitle?: string });

const runMode = computed<RunModeValue>(() => {
  if (projectMetadata.value.runMode === "quick_video") return "quick_video";
  return "pc_refine";
});

const modeTitle = computed(() => projectMetadata.value.runModeTitle || (runMode.value === "quick_video" ? "极速出片" : "Agent 制作，PC 精修"));
const resultButtonText = computed(() => (runMode.value === "quick_video" ? "查看视频结果" : "回 PC 精修"));

const percent = computed(() => {
  if (!run.value?.steps?.length) return run.value?.status === "DONE" ? 100 : 0;
  return stepProgress(run.value.steps.map((step) => step.status));
});

onLoad((query) => {
  projectId.value = String(query?.projectId || "");
  if (!projectId.value) {
    uni.showToast({ title: "缺少项目 ID", icon: "none" });
    return;
  }
  refresh();
  timer = setInterval(refreshRun, 4000);
});

onPullDownRefresh(async () => {
  await refresh();
  uni.stopPullDownRefresh();
});

onUnmounted(() => {
  if (timer) clearInterval(timer);
});

async function refresh() {
  await Promise.all([refreshProject(), refreshRun()]);
}

async function refreshProject() {
  try {
    project.value = await getProject(projectId.value);
  } catch {
    project.value = null;
  }
}

async function refreshRun() {
  if (!projectId.value) return;
  try {
    run.value = await getLatestRun(projectId.value);
  } catch (error) {
    uni.showToast({ title: error instanceof Error ? error.message : "进度读取失败", icon: "none" });
  }
}

async function pause() {
  if (!run.value?.id) return;
  run.value = await pauseRun(run.value.id);
}

async function resume() {
  if (!run.value?.id) return;
  run.value = await resumeRun(run.value.id);
}

function goResult() {
  if (run.value?.status !== "DONE") {
    uni.showToast({ title: runMode.value === "quick_video" ? "出片完成后可查看结果" : "Agent 完成后可回 PC 精修", icon: "none" });
    return;
  }
  uni.navigateTo({ url: `/pages/result/index?projectId=${projectId.value}` });
}
</script>

<style scoped lang="scss">
.progress-head {
  padding: 30rpx;
}

.progress-head__top {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 20rpx;
}

.progress-head__main {
  min-width: 0;
  flex: 1;
}

.progress-head__label {
  display: block;
  color: #5b5cf6;
  font-size: 24rpx;
  font-weight: 820;
}

.progress-head__title {
  display: block;
  margin-top: 8rpx;
  color: #101828;
  font-size: 34rpx;
  font-weight: 860;
  line-height: 1.3;
}

.progress-head__track {
  height: 16rpx;
  margin-top: 30rpx;
  overflow: hidden;
  border-radius: 999rpx;
  background: #e8ecf5;
}

.progress-head__fill {
  height: 100%;
  border-radius: 999rpx;
  background: linear-gradient(90deg, #5b5cf6, #1ea7ff);
}

.progress-head__percent {
  display: flex;
  justify-content: space-between;
  margin-top: 14rpx;
  color: #667085;
  font-size: 24rpx;
}

.progress-head__goal {
  display: block;
  margin-top: 20rpx;
  color: #667085;
  font-size: 25rpx;
  line-height: 1.58;
}

.timeline-panel {
  margin-top: 22rpx;
  padding: 20rpx 28rpx;
}

.actions {
  display: grid;
  grid-template-columns: 1fr 1.45fr;
  gap: 18rpx;
  margin-top: 26rpx;
  padding-bottom: 40rpx;
}

.actions .primary-button:only-child {
  grid-column: 1 / -1;
}
</style>
