<template>
  <view class="page home-page">
    <view class="home-head">
      <view>
        <text class="page-title">今天生成哪条短剧？</text>
        <text class="page-subtitle">极速出片拿样片，或先让 Agent 制作素材后回 PC 精修。</text>
      </view>
      <button class="home-head__mine" @tap="goMine">我的</button>
    </view>

    <view class="quick panel">
      <view class="quick__badge">AI VIDEO AGENT</view>
      <textarea
        v-model="idea"
        class="quick__textarea"
        placeholder="例如：把这个都市逆袭剧本做成 9:16 真人短剧，节奏紧凑，先生成前 10 个分镜。"
      />
      <view class="quick__actions">
        <button class="primary-button quick__primary" @tap="startQuickVideo">极速出片</button>
        <button class="secondary-button quick__secondary" @tap="goCreate">上传剧本</button>
      </view>
      <button class="ghost-button quick__refine" @tap="goCreateForRefine">Agent 制作后去 PC 精修</button>
    </view>

    <view class="home-metrics">
      <view class="home-metric">
        <text>2</text>
        <text>制作模式</text>
      </view>
      <view class="home-metric">
        <text>6</text>
        <text>自动步骤</text>
      </view>
      <view class="home-metric">
        <text>9:16</text>
        <text>默认短剧</text>
      </view>
    </view>

    <view class="section-head home-section">
      <text class="section-head__title">最近项目</text>
      <button class="section-head__action" @tap="goProjects">全部</button>
    </view>

    <view v-if="loading" class="empty panel">
      <text class="empty__title">正在读取项目</text>
      <text class="empty__desc">项目列表马上就绪。</text>
    </view>
    <view v-else-if="projects.length" class="project-list">
      <ProjectCard v-for="(project, index) in projects" :key="project.id" :project="project" :index="index" @open="openProject(project.id)" />
    </view>
    <view v-else class="empty panel">
      <text class="empty__title">还没有项目</text>
      <text class="empty__desc">先创建一个任务，后面所有 Agent 进度都会在这里汇总。</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onShow } from "@dcloudio/uni-app";
import { ref } from "vue";
import ProjectCard from "@/components/ProjectCard.vue";
import { createProject, listProjects } from "@/api/projects";
import { startAgentRun } from "@/api/agent";
import type { ProjectSummary } from "@/types/api";
import { useAuthStore } from "@/stores/auth";
import { RUN_MODES } from "@/utils/constants";

const auth = useAuthStore();
const idea = ref("");
const projects = ref<ProjectSummary[]>([]);
const loading = ref(false);

onShow(() => {
  auth.hydrate();
  if (!auth.isLoggedIn) {
    uni.reLaunch({ url: "/pages/login/index" });
    return;
  }
  fetchProjects();
});

async function fetchProjects() {
  loading.value = true;
  try {
    const result = await listProjects();
    projects.value = result.slice(0, 4);
  } catch (error) {
    uni.showToast({ title: error instanceof Error ? error.message : "项目读取失败", icon: "none" });
  } finally {
    loading.value = false;
  }
}

function createUrl(mode: "pc_refine" | "quick_video") {
  const encodedIdea = encodeURIComponent(idea.value);
  return `/pages/create/index?idea=${encodedIdea}&mode=${mode}`;
}

function goCreate() {
  uni.navigateTo({ url: createUrl("quick_video") });
}

function goCreateForRefine() {
  uni.navigateTo({ url: createUrl("pc_refine") });
}

async function startQuickVideo() {
  if (!idea.value.trim()) {
    uni.showToast({ title: "先写一句创作目标", icon: "none" });
    return;
  }

  const quickMode = RUN_MODES.find((mode) => mode.value === "quick_video") || RUN_MODES[1];

  uni.showLoading({ title: "极速出片中" });
  try {
    const project = await createProject({
      name: idea.value.slice(0, 20),
      description: idea.value,
      type: "miniapp_quick_video",
      metadata: {
        source: "miniapp",
        runMode: quickMode.value,
        runModeTitle: quickMode.title,
        quickIdea: idea.value
      }
    });
    await startAgentRun(project.id, {
      goal: idea.value,
      runIntent: quickMode.runIntent,
      selectedSteps: quickMode.selectedSteps,
      contextOptions: {
        useScriptAsset: false,
        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 {
    uni.hideLoading();
  }
}

function openProject(projectId: string | number) {
  uni.navigateTo({ url: `/pages/project-progress/index?projectId=${projectId}` });
}

function goProjects() {
  uni.switchTab({ url: "/pages/projects/index" });
}

function goMine() {
  uni.switchTab({ url: "/pages/mine/index" });
}
</script>

<style scoped lang="scss">
.home-head {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 22rpx;
}

.home-head__mine {
  min-width: 104rpx;
  height: 64rpx;
  padding: 0 22rpx;
  border-radius: 999rpx;
  background: rgba(255, 255, 255, 0.14);
  color: #ffffff;
  font-size: 24rpx;
  font-weight: 760;
}

.quick {
  margin-top: 34rpx;
  padding: 28rpx;
}

.quick__badge {
  width: fit-content;
  margin-bottom: 20rpx;
  padding: 8rpx 14rpx;
  border-radius: 999rpx;
  color: #075985;
  background: #e0f2fe;
  font-size: 20rpx;
  font-weight: 800;
}

.quick__textarea {
  width: 100%;
  min-height: 220rpx;
  color: #101828;
  font-size: 29rpx;
  line-height: 1.58;
}

.quick__actions {
  display: flex;
  gap: 18rpx;
  margin-top: 24rpx;
}

.quick__primary {
  flex: 1.15;
}

.quick__secondary {
  flex: 1;
}

.quick__refine {
  margin-top: 8rpx;
}

.home-metrics {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 14rpx;
  margin-top: 22rpx;
}

.home-metric {
  padding: 22rpx 12rpx;
  border-radius: 20rpx;
  background: #ffffff;
  text-align: center;
  box-shadow: 0 12rpx 30rpx rgba(16, 24, 40, 0.05);
}

.home-metric text:first-child {
  display: block;
  color: #101828;
  font-size: 30rpx;
  font-weight: 860;
}

.home-metric text:last-child {
  display: block;
  margin-top: 6rpx;
  color: #667085;
  font-size: 22rpx;
}

.home-section {
  margin-top: 40rpx;
  margin-bottom: 18rpx;
}

.project-list {
  display: flex;
  flex-direction: column;
  gap: 18rpx;
}
</style>
