<template>
  <view class="page">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-content">
        <view class="nav-left" @click="goBack">
          <text class="back-icon">←</text>
        </view>
        <text class="page-title">视频生成</text>
        <view class="nav-right"></view>
      </view>
    </view>

    <!-- 主内容区 -->
    <view class="main-content">
      <!-- 创建新视频按钮 -->
      <view class="create-card" @click="goToCreate">
        <text class="create-icon">🎬</text>
        <text class="create-text">创建新视频</text>
        <text class="create-hint">图片 + 音频 = 精美视频</text>
      </view>

      <!-- 视频项目列表 -->
      <view v-if="projects.length > 0" class="project-list">
        <view
          v-for="project in projects"
          :key="project.id"
          class="project-card"
          @click="openProject(project)"
        >
          <!-- 封面图 -->
          <view class="card-cover">
            <image
              v-if="project.coverUrl"
              :src="project.coverUrl"
              mode="aspectFill"
              class="cover-image"
            />
            <view v-else class="cover-placeholder">
              <text class="placeholder-icon">🎥</text>
            </view>

            <!-- 状态标签 -->
            <GenerationStatusBadge :status="project.status"></GenerationStatusBadge>


            <!-- 进度条 -->
            <view v-if="project.status === 'processing'" class="progress-overlay">
              <view class="progress-bar">
                <view class="progress-fill" :style="{ width: project.progress + '%' }"></view>
              </view>
              <text class="progress-text">{{ project.progress }}%</text>
            </view>
          </view>

          <!-- 项目信息 -->
          <view class="card-info">
            <text class="project-title">{{ project.title }}</text>
            <view class="project-meta">
              <text v-if="project.duration" class="meta-item">
                ⏱️ {{ formatDuration(project.duration) }}
              </text>
              <text v-if="project.fileSize" class="meta-item">
                📦 {{ formatFileSize(project.fileSize) }}
              </text>
            </view>
          </view>

          <!-- 操作按钮 -->
          <view class="card-actions">
            <view
              v-if="project.status === 'completed'"
              class="action-btn primary"
              @click.stop="previewVideo(project)"
            >
              预览
            </view>
            <view
              v-if="project.status === 'failed'"
              class="action-btn warning"
              @click.stop="retryGenerate(project.id)"
            >
              重试
            </view>
            <view class="action-btn danger" @click.stop="deleteProject(project.id)">
              删除
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-else class="empty-state">
        <text class="empty-icon">🎥</text>
        <text class="empty-text">暂无视频项目</text>
        <text class="empty-hint">点击上方按钮创建第一个视频</text>
      </view>

      <!-- 分页加载 -->
      <view v-if="hasMore" class="load-more" @click="loadMore">
        <text v-if="loading">加载中...</text>
        <text v-else>加载更多</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import GenerationStatusBadge from '../../components/GenerationStatusBadge';
import {
  getVideoProjects,
  deleteVideoProject,
  generateVideo,
  type VideoProjectResponse,
} from '@/utils/video-generator-api';

const projects = ref<VideoProjectResponse[]>([]);
const loading = ref(false);
const page = ref(1);
const pageSize = 10;
const hasMore = ref(true);

// 加载项目列表
async function loadProjects(reset = false) {
  if (loading.value) return;

  if (reset) {
    page.value = 1;
    projects.value = [];
    hasMore.value = true;
  }

  loading.value = true;

  try {
    const data = await getVideoProjects({ page: page.value, pageSize });
    
    if (!data || !data.items) {
      console.error('数据格式错误:', data);
      uni.showToast({ title: '数据格式错误', icon: 'none' });
      return;
    }

    if (reset) {
      projects.value = data.items;
    } else {
      projects.value.push(...data.items);
    }

    hasMore.value = data.items.length === pageSize;
    page.value++;
  } catch (error) {
    console.error('加载项目列表失败:', error);
    uni.showToast({ title: '加载失败', icon: 'none' });
  } finally {
    loading.value = false;
  }
}

// 加载更多
function loadMore() {
  if (!hasMore.value || loading.value) return;
  loadProjects();
}

function formatDuration(seconds: number): string {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins}:${secs.toString().padStart(2, '0')}`;
}

// 格式化文件大小
function formatFileSize(bytes: number): string {
  if (bytes < 1024) return bytes + 'B';
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + 'KB';
  return (bytes / (1024 * 1024)).toFixed(1) + 'MB';
}

// 返回上一页
function goBack() {
  const pages = getCurrentPages();
  if (pages.length > 1) {
    uni.navigateBack();
  } else {
    uni.switchTab({ url: '/pages/index/index' });
  }
}

// 跳转创建页
function goToCreate() {
  uni.navigateTo({ url: '/pages/video-generator/create' });
}

// 打开项目
function openProject(project: VideoProjectResponse) {
  if (project.status === 'draft') {
    uni.navigateTo({ url: `/pages/video-generator/create?id=${project.id}` });
  } else if (project.status === 'completed') {
    previewVideo(project);
  }
}

// 预览视频
function previewVideo(project: VideoProjectResponse) {
  if (!project.outputUrl) return;
  uni.navigateTo({ url: `/pages/video-generator/preview?id=${project.id}` });
}

// 重试生成
async function retryGenerate(projectId: number) {
  try {
    uni.showLoading({ title: '正在生成...' });
    await generateVideo(projectId);
    uni.hideLoading();
    uni.showToast({ title: '开始生成', icon: 'success' });
    loadProjects(true);
  } catch (error) {
    uni.hideLoading();
    console.error('生成失败:', error);
    uni.showToast({ title: '生成失败', icon: 'none' });
  }
}

// 删除项目
async function deleteProject(projectId: number) {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个视频项目吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await deleteVideoProject(projectId);
          uni.showToast({ title: '删除成功', icon: 'success' });
          loadProjects(true);
        } catch (error) {
          console.error('删除失败:', error);
          uni.showToast({ title: '删除失败', icon: 'none' });
        }
      }
    },
  });
}

// 页面显示时刷新
onShow(() => {
  loadProjects(true);
});

onMounted(() => {
  loadProjects(true);
});
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: #f5f5f5;
}

.nav-bar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px 15px;
  padding-top: max(20px, env(safe-area-inset-top));
}

.nav-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.nav-left,
.nav-right {
  width: 40px;
}

.back-icon {
  font-size: 24px;
  color: white;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: white;
}

.main-content {
  padding: 15px;
}

/* 创建卡片 */
.create-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 30px;
  margin-bottom: 20px;
  text-align: center;
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
}

.create-icon {
  font-size: 48px;
  display: block;
  margin-bottom: 10px;
}

.create-text {
  font-size: 20px;
  font-weight: 600;
  color: white;
  display: block;
  margin-bottom: 5px;
}

.create-hint {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

/* 项目列表 */
.project-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.project-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.card-cover {
  position: relative;
  height: 160px;
  background: #f0f0f0;
}

.cover-image {
  width: 100%;
  height: 100%;
}

.cover-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.placeholder-icon {
  font-size: 48px;
  opacity: 0.5;
}

/* 状态标签由 GenerationStatusBadge 组件统一管理 */

/* 进度覆盖层 */
.progress-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
  padding: 10px;
}

.progress-bar {
  height: 6px;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #667eea, #764ba2);
  transition: width 0.3s;
}

.progress-text {
  color: white;
  font-size: 12px;
  text-align: center;
  display: block;
  margin-top: 5px;
}

/* 卡片信息 */
.card-info {
  padding: 15px;
}

.project-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  display: block;
  margin-bottom: 8px;
}

.project-meta {
  display: flex;
  gap: 15px;
}

.meta-item {
  font-size: 13px;
  color: #909399;
}

/* 操作按钮 */
.card-actions {
  display: flex;
  padding: 0 15px 15px;
  gap: 10px;
}

.action-btn {
  flex: 1;
  padding: 10px;
  border-radius: 8px;
  font-size: 14px;
  text-align: center;
  background: #f5f5f5;
  color: #666;
}

.action-btn.primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.action-btn.warning {
  background: #e6a23c;
  color: white;
}

.action-btn.danger {
  background: #f56c6c;
  color: white;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.empty-icon {
  font-size: 64px;
  display: block;
  margin-bottom: 15px;
}

.empty-text {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  display: block;
  margin-bottom: 10px;
}

.empty-hint {
  font-size: 14px;
  color: #909399;
}

/* 加载更多 */
.load-more {
  text-align: center;
  padding: 20px;
  color: #409eff;
  font-size: 14px;
}
</style>
