<template>
  <view class="page create-page">
    <text class="page-title">创建视频任务</text>
    <text class="page-subtitle">选择制作模式后上传剧本，Agent 会按不同链路推进。</text>

    <view class="mode-switch">
      <button
        v-for="mode in RUN_MODES"
        :key="mode.value"
        class="mode-switch__item"
        :class="{ 'mode-switch__item--active': runMode === mode.value }"
        @tap="runMode = mode.value"
      >
        <text>{{ mode.label }}</text>
      </button>
    </view>

    <view class="mode-card panel">
      <text class="mode-card__title">{{ selectedMode.title }}</text>
      <text class="mode-card__desc">{{ selectedMode.description }}</text>
    </view>

    <view class="form panel">
      <view>
        <text class="field-label">项目名称</text>
        <input v-model="projectName" class="field-input" placeholder="例如：都市逆袭第 1 集" />
      </view>

      <UploadPanel :file-name="fileName" @picked="handlePicked" />

      <view>
        <text class="field-label">制作目标</text>
        <textarea v-model="goal" class="field-textarea" placeholder="描述你希望生成的视频风格、比例、集数、节奏或重点角色。" />
      </view>

      <view class="option-grid">
        <view class="option">
          <text class="option__label">风格</text>
          <picker :range="styleLabels" :value="styleIndex" @change="styleIndex = Number($event.detail.value)">
            <text class="option__value">{{ styleLabels[styleIndex] }}</text>
          </picker>
        </view>
        <view class="option">
          <text class="option__label">画幅</text>
          <picker :range="ASPECT_RATIOS" :value="ratioIndex" @change="ratioIndex = Number($event.detail.value)">
            <text class="option__value">{{ ASPECT_RATIOS[ratioIndex] }}</text>
          </picker>
        </view>
        <view class="option">
          <text class="option__label">清晰度</text>
          <picker :range="RESOLUTIONS" :value="resolutionIndex" @change="resolutionIndex = Number($event.detail.value)">
            <text class="option__value">{{ RESOLUTIONS[resolutionIndex] }}</text>
          </picker>
        </view>
      </view>

      <button class="primary-button" :loading="submitting" @tap="submit">{{ selectedMode.actionLabel }}</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import UploadPanel from "@/components/UploadPanel.vue";
import { createProject, uploadScript } from "@/api/projects";
import { startAgentRun } from "@/api/agent";
import { ASPECT_RATIOS, PROJECT_STYLES, RESOLUTIONS, RUN_MODES, type RunModeValue } from "@/utils/constants";

const projectName = ref("");
const goal = ref("");
const filePath = ref("");
const fileName = ref("");
const styleIndex = ref(0);
const ratioIndex = ref(0);
const resolutionIndex = ref(1);
const runMode = ref<RunModeValue>("pc_refine");
const submitting = ref(false);

const styleLabels = computed(() => PROJECT_STYLES.map((item) => item.label));
const selectedMode = computed(() => RUN_MODES.find((mode) => mode.value === runMode.value) || RUN_MODES[0]);

onLoad((query) => {
  const idea = query?.idea ? decodeURIComponent(String(query.idea)) : "";
  const mode = query?.mode ? String(query.mode) : "";
  goal.value = idea;
  projectName.value = idea ? idea.slice(0, 20) : "";

  if (mode === "pc_refine" || mode === "quick_video") {
    runMode.value = mode;
  }
});

function handlePicked(file: { path: string; name: string }) {
  filePath.value = file.path;
  fileName.value = file.name;
  if (!projectName.value) {
    projectName.value = file.name.replace(/\.[^.]+$/, "");
  }
}

async function submit() {
  if (!projectName.value.trim()) {
    uni.showToast({ title: "请输入项目名称", icon: "none" });
    return;
  }
  if (!goal.value.trim()) {
    uni.showToast({ title: "请输入制作目标", icon: "none" });
    return;
  }

  submitting.value = true;
  uni.showLoading({ title: runMode.value === "quick_video" ? "出片中" : "启动中" });
  try {
    const mode = selectedMode.value;
    const project = await createProject({
      name: projectName.value,
      description: goal.value,
      type: PROJECT_STYLES[styleIndex.value].value,
      aspectRatio: ASPECT_RATIOS[ratioIndex.value],
      resolution: RESOLUTIONS[resolutionIndex.value],
      metadata: {
        source: "miniapp",
        runMode: mode.value,
        runModeTitle: mode.title,
        style: PROJECT_STYLES[styleIndex.value],
        aspectRatio: ASPECT_RATIOS[ratioIndex.value],
        resolution: RESOLUTIONS[resolutionIndex.value]
      }
    });

    if (filePath.value) {
      await uploadScript(project.id, filePath.value);
    }

    await startAgentRun(project.id, {
      goal: goal.value,
      runIntent: mode.runIntent,
      selectedSteps: mode.selectedSteps,
      contextOptions: {
        useScriptAsset: Boolean(filePath.value),
        useExistingOutline: true,
        useExistingEpisodes: true,
        useExistingAssets: true,
        useExistingStoryboards: true
      }
    });

    uni.navigateTo({ url: `/pages/project-progress/index?projectId=${project.id}` });
  } catch (error) {
    uni.showToast({ title: error instanceof Error ? error.message : "启动失败", icon: "none" });
  } finally {
    submitting.value = false;
    uni.hideLoading();
  }
}
</script>

<style scoped lang="scss">
.mode-switch {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 10rpx;
  margin-top: 34rpx;
  padding: 8rpx;
  border-radius: 22rpx;
  background: rgba(255, 255, 255, 0.12);
}

.mode-switch__item {
  min-height: 80rpx;
  border-radius: 16rpx;
  color: rgba(255, 255, 255, 0.72);
  font-size: 27rpx;
  font-weight: 800;
  display: flex;
  align-items: center;
  justify-content: center;
}

.mode-switch__item--active {
  background: #ffffff;
  color: #101828;
  box-shadow: 0 14rpx 30rpx rgba(0, 0, 0, 0.16);
}

.mode-card {
  margin-top: 18rpx;
  padding: 28rpx;
}

.mode-card__title {
  display: block;
  color: #101828;
  font-size: 31rpx;
  font-weight: 860;
}

.mode-card__desc {
  display: block;
  margin-top: 10rpx;
  color: #667085;
  font-size: 25rpx;
  line-height: 1.58;
}

.form {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
  margin-top: 24rpx;
  padding: 28rpx;
}

.option-grid {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 14rpx;
}

.option {
  min-height: 118rpx;
  padding: 20rpx;
  border-radius: 18rpx;
  background: #f6f8fc;
}

.option__label {
  display: block;
  color: #667085;
  font-size: 22rpx;
}

.option__value {
  display: block;
  margin-top: 14rpx;
  color: #101828;
  font-size: 27rpx;
  font-weight: 820;
}
</style>
