<template>
  <div class="video-detail-page">
    <!-- 左侧导航栏 -->
    <aside class="sidebar">
      <!-- Logo -->
      <div class="logo">
        <img src="/images/backgrounds/logo.svg?v=2" alt="Logo" />
      </div>
      
      <!-- 导航菜单 -->
      <nav class="nav-menu">
        <div class="nav-item" @click="goToProfile">
          <UserOutlined />
          <span>个人主页</span>
        </div>
        <div class="nav-item" @click="goToSubscription">
          <CompassOutlined />
          <span>会员订阅</span>
        </div>
        <div class="nav-item active">
          <FileOutlined />
          <span>我的作品</span>
        </div>
      </nav>
    </aside>
    
    <!-- 主内容区域 -->
    <main class="main-content">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <LoadingOutlined class="is-loading" style="font-size: 40px" />
        <p>{{ $t('common.loading') }}</p>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="error-container">
        <CloseCircleOutlined style="font-size: 60px; color: #f56c6c" />
        <p>{{ error }}</p>
        <a-button type="primary" @click="loadVideoData">重试</a-button>
        <a-button @click="goBack">返回</a-button>
      </div>

      <!-- 正常内容 -->
      <template v-else>
      <!-- 左侧视频播放器区域 -->
      <div class="video-player-section">
        <div class="video-container">
          <video 
            ref="videoPlayer"
            class="video-player"
            :src="videoData.videoUrl"
            :poster="videoData.cover"
            @loadedmetadata="onVideoLoaded"
            @timeupdate="onTimeUpdate"
            @ended="onVideoEnded"
          >
            您的浏览器不支持视频播放
          </video>
          
          <!-- 视频文字叠加 已移除（用户要求） -->
          
          <!-- 播放控制栏 -->
          <div class="video-controls">
            <div class="control-left">
              <button class="play-btn" @click="togglePlay">
                <PlayCircleOutlined v-if="!isPlaying" />
                <PauseOutlined v-else />
              </button>
              <div class="progress-container">
                <div class="progress-bar" @click="seekTo">
                  <div class="progress-fill" :style="{ width: progressPercent + '%' }"></div>
                </div>
                <div class="time-display">{{ formatTime(currentTime) }} / {{ formatTime(duration) }}</div>
              </div>
            </div>
            <div class="control-right">
              <button class="control-btn" @click="toggleFullscreen">
                <FullscreenOutlined />
              </button>
            </div>
          </div>
          
          <!-- 右上角操作按钮 -->
          <div class="video-actions">
            <a-tooltip :content="$t('video.download')" placement="bottom">
              <button class="action-btn" @click="downloadVideo">
                <DownloadOutlined />
              </button>
            </a-tooltip>
            <a-tooltip :content="$t('common.delete')" placement="bottom">
              <button class="action-btn delete-btn" @click="deleteVideo">
                <DeleteOutlined />
              </button>
            </a-tooltip>
          </div>
        </div>
      </div>
      
      <!-- 右侧详情侧边栏 -->
      <div class="detail-sidebar">
        <!-- 用户信息头部 -->
        <div class="sidebar-header">
          <div class="user-info">
            <div class="avatar">
              <img src="/images/backgrounds/avatar-default.svg" :alt="$t('dashboard.userAvatar')" class="avatar-image" />
            </div>
            <div class="username">{{ videoData.username }}</div>
          </div>
          <button class="close-btn" @click="goBack">
            <CloseOutlined />
          </button>
        </div>
        
        <!-- 标签页 -->
        <div class="tabs">
          <div class="tab active">视频详情</div>
          <div class="tab">文生视频</div>
        </div>
        
        <!-- 提示词区域 -->
        <div class="description-section">
          <h3 class="section-title">提示词</h3>
          <p class="description-text">{{ videoData.description }}</p>
        </div>
        
        <!-- 元数据区域 -->
        <div class="metadata-section">
          <div class="metadata-item">
            <span class="label">创建时间</span>
            <span class="value">{{ videoData.createTime }}</span>
          </div>
          <div class="metadata-item">
            <span class="label">视频 ID</span>
            <span class="value">{{ videoData.id }}</span>
          </div>
          <div class="metadata-item">
            <span class="label">时长</span>
            <span class="value">{{ videoData.duration }}s</span>
          </div>
          <div class="metadata-item">
            <span class="label">清晰度</span>
            <span class="value">{{ videoData.resolution }}</span>
          </div>
          <div class="metadata-item">
            <span class="label">分类</span>
            <span class="value">{{ videoData.category }}</span>
          </div>
          <div class="metadata-item">
            <span class="label">宽高比</span>
            <span class="value">{{ videoData.aspectRatio }}</span>
          </div>
        </div>
        
        <!-- 操作按钮 -->
        <div class="action-section">
          <button class="create-similar-btn" @click="createSimilar">
            做同款
          </button>
        </div>
      </div>
      </template>
    </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 { useI18n } from 'vue-i18n'
import {
  PlayCircleOutlined,
  PauseOutlined,
  FullscreenOutlined,
  DownloadOutlined,
  DeleteOutlined,
  UserOutlined,
  CompassOutlined,
  FileOutlined,
  CloseOutlined,
  LoadingOutlined,
  CloseCircleOutlined
} from '@ant-design/icons-vue'
import { getWorkDetail } from '@/api/userWorks'

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

// 视频播放器相关
const videoPlayer = ref(null)
const isPlaying = ref(false)
const currentTime = ref(0)
const duration = ref(0)
const progressPercent = ref(0)

// 加载状态
const loading = ref(true)
const error = ref(null)

// 视频数据
const videoData = ref({
  id: '',
  username: '',
  title: '',
  description: '',
  createTime: '',
  duration: '',
  resolution: '',
  category: '',
  aspectRatio: '',
  videoUrl: '',
  cover: ''
})

// 处理URL，确保相对路径正确
const processUrl = (url) => {
  if (!url) return null
  // data: 协议（Base64 图片/视频等）直接返回
  if (url.startsWith('data:')) {
    return url
  }
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  if (url.startsWith('/')) {
    return url
  }
  return '/' + url
}

// 获取视频数据
const loadVideoData = async () => {
  const videoId = route.params.id
  if (!videoId) {
    error.value = t('common.missingVideoId')
    loading.value = false
    message.error(t('common.missingVideoId'))
    return
  }

  try {
    loading.value = true
    const response = await getWorkDetail(videoId)

    if (response.data.success) {
      const work = response.data.data

      // 转换数据格式
      const resultUrl = processUrl(work.resultUrl)
      const thumbnailUrl = processUrl(work.thumbnailUrl)

      videoData.value = {
        id: work.taskId || work.id?.toString() || '',
        username: work.username || work.user?.username || t('common.unknownUser'),
        title: work.title || work.prompt || t('common.untitledWork'),
        description: work.prompt || work.description || t('common.noPrompt'),
        createTime: work.createdAt ? new Date(work.createdAt).toLocaleString('zh-CN') : '',
        date: work.createdAt ? new Date(work.createdAt).toLocaleDateString('zh-CN') : '',
        duration: work.duration || work.videoDuration || work.length || 5,
        resolution: work.quality || work.resolution || '1080p',
        category: work.workType === 'TEXT_TO_VIDEO' ? t('common.textToVideoCategory') :
                 work.workType === 'IMAGE_TO_VIDEO' ? t('common.imageToVideoCategory') :
                 work.workType === 'STORYBOARD_VIDEO' ? t('common.storyboardVideoCategory') : t('common.unknownCategory'),
        aspectRatio: work.aspectRatio || work.ratio || work.aspect || '16:9',
        videoUrl: resultUrl || thumbnailUrl || '/images/backgrounds/welcome.jpg',
        cover: thumbnailUrl || resultUrl || '/images/backgrounds/welcome.jpg'
      }

      error.value = null
    } else {
      throw new Error(response.data.message || t('common.loadWorkDetailFailed'))
    }
  } catch (err) {
    console.error('加载视频数据失败:', err)
    error.value = err.message || t('common.loadWorkDetailFailed')
    message.error(t('common.loadWorkDetailFailed') + ': ' + (err.message || ''))
  } finally {
    loading.value = false
  }
}

// 视频播放控制
const togglePlay = () => {
  if (!videoPlayer.value) return
  
  if (isPlaying.value) {
    videoPlayer.value.pause()
  } else {
    videoPlayer.value.play()
  }
}

const onVideoLoaded = () => {
  duration.value = videoPlayer.value.duration
}

const onTimeUpdate = () => {
  currentTime.value = videoPlayer.value.currentTime
  progressPercent.value = (currentTime.value / duration.value) * 100
}

const onVideoEnded = () => {
  isPlaying.value = false
}

const seekTo = (event) => {
  if (!videoPlayer.value) return
  
  const rect = event.currentTarget.getBoundingClientRect()
  const clickX = event.clientX - rect.left
  const percentage = clickX / rect.width
  const newTime = percentage * duration.value
  
  videoPlayer.value.currentTime = newTime
}

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 (!videoPlayer.value) return
  
  if (document.fullscreenElement) {
    document.exitFullscreen()
  } else {
    videoPlayer.value.requestFullscreen()
  }
}

// 操作功能
const downloadVideo = async () => {
  if (!videoData.value.videoUrl) {
    message.warning(t('common.videoLinkUnavailable'))
    return
  }
  
  try {
    message.info(t('common.preparingDownload'))
    
    // 获取视频文件
    const response = await fetch(videoData.value.videoUrl)
    const blob = await response.blob()
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `${videoData.value.title || 'video'}_${Date.now()}.mp4`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    message.success(t('common.downloadStarted'))
  } catch (error) {
    console.error('下载失败:', error)
    // 备用方案：直接打开链接
    window.open(videoData.value.videoUrl, '_blank')
  }
}

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'))
    router.back()
  } catch (_) {}
}

const createSimilar = () => {
  message.info(t('common.jumpToTextToVideo'))
  // router.push('/create-video')
}

// 导航函数
const goToProfile = () => {
  router.push('/profile')
}

const goToSubscription = () => {
  router.push('/subscription')
}

const goBack = () => {
  router.back()
}

// 监听视频播放状态变化
const handlePlay = () => {
  isPlaying.value = true
}

const handlePause = () => {
  isPlaying.value = false
}

onMounted(async () => {
  // 加载视频数据
  await loadVideoData()

  if (videoPlayer.value) {
    videoPlayer.value.addEventListener('play', handlePlay)
    videoPlayer.value.addEventListener('pause', handlePause)
  }
})

onUnmounted(() => {
  if (videoPlayer.value) {
    videoPlayer.value.removeEventListener('play', handlePlay)
    videoPlayer.value.removeEventListener('pause', handlePause)
  }
})
</script>

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

/* 左侧导航栏 */
.sidebar {
  width: var(--sidebar-width);
  background: var(--bg-base);
  padding: var(--space-6) 0;
  border-right: 1px solid var(--border-default);
  flex-shrink: 0;
  display: block;
  position: relative;
}

.logo {
  padding: 0 var(--space-6) var(--space-8);
  display: flex;
  align-items: center;
  justify-content: center;
}

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

.nav-menu {
  padding: 0 var(--space-5);
}

.nav-item {
  display: flex;
  align-items: center;
  padding: 14px 18px;
  margin-bottom: var(--space-1);
  border-radius: var(--radius-md);
  cursor: pointer;
  transition: var(--transition-all);
  position: relative;
}

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

.nav-item.active {
  background: var(--primary-900);
}

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

.nav-item span {
  font-size: var(--text-base);
  flex: 1;
}

/* 主内容区域 */
.main-content {
  flex: 1;
  display: flex;
  background: var(--bg-base);
  overflow: hidden;
}

/* 加载状态 */
.loading-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--text-primary);
  gap: var(--space-5);
}

.loading-container p {
  font-size: var(--text-base);
  color: var(--text-tertiary);
}

/* 错误状态 */
.error-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--text-primary);
  gap: var(--space-5);
}

.error-container p {
  font-size: var(--text-base);
  color: var(--error-400);
  max-width: 400px;
  text-align: center;
}

/* 左侧视频播放器区域 */
.video-player-section {
  flex: 2;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--bg-root);
  position: relative;
}

.video-container {
  position: relative;
  width: 100%;
  height: 100%;
  max-width: 100%;
  max-height: 100%;
}

.video-player {
  width: 100%;
  height: 100%;
  object-fit: contain;
  background: var(--bg-root);
}

/* video overlay 样式已移除（不再使用 overlayText） */

/* 视频控制栏 */
.video-controls {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
  padding: var(--space-5);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.control-left {
  display: flex;
  align-items: center;
  gap: var(--space-4);
  flex: 1;
}

.play-btn {
  background: none;
  border: none;
  color: var(--text-primary);
  font-size: var(--text-xl);
  cursor: pointer;
  padding: var(--space-2);
  border-radius: var(--radius-full);
  transition: background-color var(--duration-normal) var(--ease-default);
}

.play-btn:hover {
  background: var(--bg-active);
}

.progress-container {
  flex: 1;
  display: flex;
  align-items: center;
  gap: var(--space-3);
}

.progress-bar {
  flex: 1;
  height: 4px;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 2px;
  cursor: pointer;
  position: relative;
}

.progress-fill {
  height: 100%;
  background: var(--primary-500);
  border-radius: 2px;
  transition: width 0.1s;
}

.time-display {
  color: var(--text-primary);
  font-size: var(--text-sm);
  white-space: nowrap;
}

.control-right {
  display: flex;
  align-items: center;
}

.control-btn {
  background: none;
  border: none;
  color: var(--text-primary);
  font-size: var(--text-lg);
  cursor: pointer;
  padding: var(--space-2);
  border-radius: var(--radius-sm);
  transition: background-color var(--duration-normal) var(--ease-default);
}

.control-btn:hover {
  background: var(--bg-active);
}

/* 右上角操作按钮 */
.video-actions {
  position: absolute;
  top: var(--space-5);
  right: var(--space-5);
  display: flex;
  gap: var(--space-3);
  z-index: var(--z-base);
}

.action-btn {
  background: rgba(255, 255, 255, 0.9);
  border: none;
  color: var(--text-inverse);
  width: 40px;
  height: 40px;
  border-radius: var(--radius-full);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: var(--transition-all);
  box-shadow: var(--shadow-sm);
}

.action-btn:hover {
  background: #fff;
  transform: scale(1.1);
  box-shadow: var(--shadow-md);
}

.delete-btn:hover {
  background: var(--error-glow);
  color: var(--error-600);
}

/* 右侧详情侧边栏 */
.detail-sidebar {
  flex: 1;
  background: var(--bg-surface);
  border-radius: var(--radius-lg) 0 0 0;
  padding: var(--space-6);
  display: flex;
  flex-direction: column;
  gap: var(--space-6);
  overflow-y: auto;
}

.sidebar-header {
  display: flex;
  flex-direction: column;
  gap: var(--space-4);
}

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

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

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

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

.tabs {
  display: flex;
  gap: 0;
}

.tab {
  padding: var(--space-2) var(--space-4);
  background: transparent;
  color: var(--text-tertiary);
  cursor: pointer;
  border-radius: var(--radius-sm);
  transition: var(--transition-all);
  font-size: var(--text-sm);
}

.tab.active {
  background: var(--primary-500);
  color: var(--text-primary);
}

.tab:hover:not(.active) {
  background: var(--bg-active);
  color: var(--text-primary);
}

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

.section-title {
  font-size: var(--text-base);
  font-weight: var(--font-semibold);
  color: var(--text-primary);
  margin: 0;
}

.description-text {
  font-size: var(--text-sm);
  line-height: var(--leading-relaxed);
  color: var(--text-secondary);
  margin: 0;
}

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

.metadata-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--space-2) 0;
}

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

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

.action-section {
  margin-top: auto;
  padding-top: var(--space-5);
}

.create-similar-btn {
  width: 100%;
  background: var(--primary-500);
  color: var(--text-primary);
  border: none;
  border-radius: var(--radius-md);
  padding: var(--space-3) var(--space-6);
  font-size: var(--text-base);
  font-weight: var(--font-medium);
  cursor: pointer;
  transition: var(--transition-all);
}

.create-similar-btn:hover {
  background: var(--primary-700);
  transform: translateY(-2px);
}

.create-similar-btn:active {
  transform: translateY(0);
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .video-detail-page {
    flex-direction: column;
  }
  
  .video-player-section {
    flex: 1;
    min-height: 50vh;
  }
  
  .detail-sidebar {
    flex: 1;
    border-radius: 0;
  }
}

@media (max-width: 768px) {
  .video-overlay {
    bottom: 60px;
    left: 10px;
  }
  
  .overlay-text {
    font-size: 18px;
  }
  
  .video-controls {
    padding: 15px;
  }
  
  .video-actions {
    top: 15px;
    right: 15px;
    gap: 8px;
  }
  
  .action-btn {
    width: 35px;
    height: 35px;
  }
  
  .detail-sidebar {
    padding: var(--space-4);
    gap: var(--space-4);
  }
}
</style>
