<template>
  <div class="video-detail-page">
    <!-- 顶部导航栏 -->
    <div class="top-bar">
      <div class="logo">
        <img src="/images/backgrounds/logo.png" alt="Logo" />
      </div>
      <div class="top-actions">
        <UserOutlined class="action-icon" />
        <SettingOutlined class="action-icon" />
      </div>
    </div>

    <!-- 左侧导航栏 -->
    <aside class="sidebar">
      <div class="nav-item">
        <FileOutlined />
        <span>{{ $t('imageDetail.files') }}</span>
      </div>
      <div class="nav-item">
        <PictureOutlined />
        <span>{{ $t('imageDetail.images') }}</span>
      </div>
      <div class="nav-item">
        <PlayCircleOutlined />
        <span>{{ $t('imageDetail.videos') }}</span>
      </div>
    </aside>

    <!-- 主内容区域 -->
    <main class="main-content">
      <!-- 视频播放器区域 -->
      <div class="video-section">
        <div class="video-player">
          <video 
            ref="videoRef"
            :src="videoData.videoUrl" 
            @click="togglePlay"
            @timeupdate="updateTime"
            @loadedmetadata="onLoadedMetadata"
          >
            {{ $t('imageDetail.browserNotSupport') }}
          </video>
          
          <!-- 视频控制栏 -->
          <div class="video-controls" v-show="showControls">
            <div class="controls-left">
              <a-button circle size="small" @click="togglePlay">
                <PlayCircleOutlined v-if="!isPlaying" /><PauseCircleOutlined v-else />
              </a-button>
              <span class="time-display">{{ formatTime(currentTime) }} / {{ formatTime(duration) }}</span>
            </div>
            <div class="controls-right">
              <a-button circle size="small" @click="toggleFullscreen">
                <FullscreenOutlined />
              </a-button>
            </div>
          </div>

          <!-- 视频操作按钮 -->
          <div class="video-actions">
            <a-tooltip :content="$t('video.download')" placement="bottom">
              <a-button circle size="small" @click="downloadVideo">
                <DownloadOutlined />
              </a-button>
            </a-tooltip>
            <a-tooltip :content="$t('common.delete')" placement="bottom">
              <a-button circle size="small" @click="deleteVideo">
                <DeleteOutlined />
              </a-button>
            </a-tooltip>
          </div>
        </div>
      </div>

      <!-- 右侧详情区域 -->
      <div class="detail-section">
        <div class="detail-header">
          <h3>{{ $t('imageDetail.imageDetail') }}</h3>
          <p class="subtitle">{{ $t('video.imageToVideo.referenceImage') }}</p>
        </div>

        <div class="detail-content">
          <div class="input-section">
            <a-input 
              v-model="detailInput" 
              :placeholder="$t('imageToVideoDetail.detailInputPlaceholder')"
              type="textarea"
              :rows="3"
            />
          </div>

          <div class="thumbnails">
            <div class="thumbnail" v-for="(thumb, index) in thumbnails" :key="index">
              <img :src="thumb" :alt="`${$t('works.image')}${index + 1}`" />
            </div>
          </div>

          <div class="description">
            <h4>{{ $t('works.description') }}</h4>
            <p>{{ videoData.description }}</p>
          </div>

          <div class="metadata">
            <div class="meta-item">
              <span class="label">{{ $t('imageDetail.createTime') }}</span>
              <span class="value">{{ videoData.createTime }}</span>
            </div>
            <div class="meta-item">
              <span class="label">{{ $t('imageDetail.videoId') }}</span>
              <span class="value">{{ videoData.id }}</span>
            </div>
            <div class="meta-item">
              <span class="label">{{ $t('imageDetail.duration') }}</span>
              <span class="value">{{ videoData.duration }}s</span>
            </div>
            <div class="meta-item">
              <span class="label">{{ $t('imageDetail.quality') }}</span>
              <span class="value">{{ videoData.resolution }}</span>
            </div>
            <div class="meta-item">
              <span class="label">{{ $t('imageDetail.aspectRatio') }}</span>
              <span class="value">{{ videoData.aspectRatio }}</span>
            </div>
          </div>

          <div class="action-button">
            <a-button type="primary" size="large" @click="makeSimilar">
              {{ $t('imageDetail.createSimilar') }}
            </a-button>
          </div>
        </div>

        <!-- 滚动指示器 -->
        <div class="scroll-indicators">
          <ArrowUpOutlined class="scroll-arrow up" />
          <DownOutlined class="scroll-arrow down" />
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import { imageToVideoApi } from '@/api/imageToVideo'
import { useI18n } from 'vue-i18n'
import {
  UserOutlined, SettingOutlined, FileOutlined, PictureOutlined, PlayCircleOutlined, PauseCircleOutlined,
  FullscreenOutlined, DownloadOutlined, DeleteOutlined, ArrowUpOutlined, DownOutlined
} from '@ant-design/icons-vue'

const { t } = useI18n()
const route = useRoute()
const router = useRouter()
const videoRef = ref(null)

// 视频播放状态
const isPlaying = ref(false)
const currentTime = ref(0)
const duration = ref(0)
const showControls = ref(true)
const loading = ref(true)

// 详情数据
const detailInput = ref('')
const videoData = ref({
  id: '',
  videoUrl: '',
  description: '',
  createTime: '',
  duration: 5,
  resolution: '1080p',
  aspectRatio: '16:9',
  status: 'PROCESSING',
  progress: 0
})

const thumbnails = ref([
  '/images/backgrounds/welcome.jpg',
  '/images/backgrounds/welcome.jpg'
])

// 视频控制方法
const togglePlay = () => {
  if (!videoRef.value) return
  
  if (isPlaying.value) {
    videoRef.value.pause()
  } else {
    videoRef.value.play()
  }
  isPlaying.value = !isPlaying.value
}

const updateTime = () => {
  if (videoRef.value) {
    currentTime.value = videoRef.value.currentTime
  }
}

const onLoadedMetadata = () => {
  if (videoRef.value) {
    duration.value = videoRef.value.duration
  }
}

const formatTime = (time) => {
  const minutes = Math.floor(time / 60)
  const seconds = Math.floor(time % 60)
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

const toggleFullscreen = () => {
  if (!videoRef.value) return
  
  if (document.fullscreenElement) {
    document.exitFullscreen()
  } else {
    videoRef.value.requestFullscreen()
  }
}

// 操作按钮方法
const downloadVideo = () => {
  message.success(t('common.downloadStarted'))
}

const deleteVideo = async () => {
  try {
    await new Promise((resolve, reject) => {
      Modal.confirm({
        title: t('common.confirm'),
        content: t('common.confirm'),
        okText: t('common.delete'),
        cancelText: t('common.cancel'),
        onOk() { resolve() },
        onCancel() { reject('cancel') }
      })
    })
    message.success(t('common.videoDeleted'))
  } catch (_) {}
}

const makeSimilar = () => {
  message.info(t('common.retryFeatureInDev'))
}

// 自动隐藏控制栏
let controlsTimer = null
const resetControlsTimer = () => {
  clearTimeout(controlsTimer)
  showControls.value = true
  controlsTimer = setTimeout(() => {
    showControls.value = false
  }, 3000)
}

// 加载任务详情
const loadTaskDetail = async () => {
  const taskId = route.params.taskId
  if (!taskId) {
    message.error(t('common.missingVideoId'))
    router.push('/image-to-video')
    return
  }
  
  try {
    loading.value = true
    const response = await imageToVideoApi.getTaskDetail(taskId)
    
    if (response.data && response.data.success && response.data.data) {
      const task = response.data.data
      videoData.value = {
        id: task.taskId || taskId,
        videoUrl: task.resultUrl || '',
        description: task.prompt || '',
        createTime: task.createdAt || new Date().toISOString(),
        duration: task.duration || 5,
        resolution: task.hdMode ? '1080p' : '720p',
        aspectRatio: task.aspectRatio || '16:9',
        status: task.status || 'PROCESSING',
        progress: task.progress || 0
      }
      
      // 如果任务已完成且有视频URL，设置视频源
      if (task.status === 'COMPLETED' && task.resultUrl) {
        videoData.value.videoUrl = task.resultUrl
      }
    } else {
      message.error(response.data?.message || t('common.loadWorkDetailFailed'))
      router.push('/image-to-video')
    }
  } catch (error) {
    console.error('加载任务详情失败:', error)
    message.error(t('common.loadWorkDetailFailed'))
    router.push('/image-to-video')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  // 加载任务详情
  loadTaskDetail()
  
  // 监听鼠标移动来显示/隐藏控制栏
  document.addEventListener('mousemove', resetControlsTimer)
  resetControlsTimer()
})

onUnmounted(() => {
  clearTimeout(controlsTimer)
  document.removeEventListener('mousemove', resetControlsTimer)
})
</script>

<style scoped>
.video-detail-page {
  height: 100vh;
  background: var(--bg-base);
  color: var(--text-primary);
  display: flex;
  flex-direction: column;
  font-family: var(--font-sans);
}

/* 顶部导航栏 */
.top-bar {
  height: 60px;
  background: var(--bg-surface);
  border-bottom: 1px solid var(--border-default);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  z-index: 100;
}

.logo {
  display: flex;
  align-items: center;
}

.logo img {
  height: 30px;
  width: auto;
}

.top-actions {
  display: flex;
  gap: var(--space-4);
}

.action-icon {
  font-size: var(--text-xl);
  color: var(--text-secondary);
  cursor: pointer;
  transition: color var(--duration-normal) var(--ease-default);
}

.action-icon:hover {
  color: var(--text-primary);
}

/* 左侧导航栏 */
.sidebar {
  position: fixed;
  left: 0;
  top: 60px;
  width: 200px;
  height: calc(100vh - 60px);
  background: var(--bg-surface);
  border-right: 1px solid var(--border-default);
  padding: 20px 0;
  z-index: 90;
}

.nav-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  color: var(--text-secondary);
  cursor: pointer;
  transition: var(--transition-all);
}

.nav-item:hover {
  background: var(--bg-hover);
  color: var(--text-primary);
}

.nav-item .anticon {
  margin-right: 12px;
  font-size: var(--text-lg);
}

/* 主内容区域 */
.main-content {
  margin-left: 200px;
  margin-top: 60px;
  height: calc(100vh - 60px);
  display: flex;
}

/* 视频播放器区域 */
.video-section {
  flex: 2;
  padding: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-player {
  position: relative;
  width: 100%;
  max-width: 800px;
  aspect-ratio: 16/9;
  background: var(--bg-base);
  border-radius: var(--radius-md);
  overflow: hidden;
}

.video-player video {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
}

.video-controls {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0,0,0,0.8));
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.controls-left {
  display: flex;
  align-items: center;
  gap: var(--space-3);
}

.time-display {
  color: var(--text-primary);
  font-size: var(--text-sm);
  font-family: monospace;
}

.video-actions {
  position: absolute;
  top: 20px;
  right: 20px;
  display: flex;
  gap: var(--space-2);
}

.video-actions .ant-btn {
  background: rgba(0,0,0,0.6);
  border: 1px solid rgba(255,255,255,0.2);
  color: var(--text-primary);
}

.video-actions .ant-btn:hover {
  background: rgba(0,0,0,0.8);
  border-color: rgba(255,255,255,0.4);
}

/* 右侧详情区域 */
.detail-section {
  flex: 1;
  background: var(--bg-surface);
  border-left: 1px solid var(--border-default);
  padding: 20px;
  overflow-y: auto;
  position: relative;
}

.detail-header h3 {
  font-size: var(--text-xl);
  font-weight: var(--font-semibold);
  margin-bottom: 4px;
  color: var(--text-primary);
}

.subtitle {
  color: var(--text-tertiary);
  font-size: var(--text-sm);
  margin-bottom: 20px;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: var(--space-5);
}

.input-section {
  margin-bottom: 10px;
}

.thumbnails {
  display: flex;
  gap: var(--space-2);
}

.thumbnail {
  width: 60px;
  height: 60px;
  border-radius: var(--radius-sm);
  overflow: hidden;
  background: var(--bg-hover);
}

.thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.description h4 {
  font-size: var(--text-base);
  font-weight: var(--font-semibold);
  margin-bottom: 8px;
  color: var(--text-primary);
}

.description p {
  color: var(--text-secondary);
  font-size: var(--text-sm);
  line-height: 1.5;
}

.metadata {
  display: flex;
  flex-direction: column;
  gap: var(--space-3);
}

.meta-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid var(--border-subtle);
}

.meta-item:last-child {
  border-bottom: none;
}

.label {
  color: var(--text-tertiary);
  font-size: var(--text-sm);
}

.value {
  color: var(--text-primary);
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
}

.action-button {
  margin-top: 20px;
}

.action-button .ant-btn {
  width: 100%;
  height: 44px;
  font-size: var(--text-base);
  font-weight: var(--font-semibold);
}

.scroll-indicators {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
  gap: var(--space-2);
}

.scroll-arrow {
  font-size: var(--text-base);
  color: var(--text-muted);
  cursor: pointer;
  transition: color var(--duration-normal) var(--ease-default);
}

.scroll-arrow:hover {
  color: var(--text-tertiary);
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .sidebar {
    width: 160px;
  }
  
  .main-content {
    margin-left: 160px;
  }
  
  .video-section {
    padding: 10px;
  }
  
  .detail-section {
    padding: 15px;
  }
}

@media (max-width: 768px) {
  .sidebar {
    display: none;
  }
  
  .main-content {
    margin-left: 0;
    flex-direction: column;
  }
  
  .video-section {
    flex: none;
    height: 50vh;
  }
  
  .detail-section {
    flex: none;
    height: 50vh;
  }
}
</style>
