<template>
  <div class="file-preview-panel">
    <!-- 标题栏 -->
    <div class="preview-header">
      <Icon :icon="headerIcon" :size="18" :style="{ color: fileColor }" />
      <h3 class="preview-title">{{ row?.file_name || '—' }}</h3>
      <button class="close-btn" @click="$emit('close')" :title="t('Close')">
        <Icon icon="tabler:x" :size="18" />
      </button>
    </div>

    <!-- 滚动区域 -->
    <div class="preview-body">
      <!-- ① 主预览区 -->
      <div class="preview-visual">
        <!-- 图片预览 -->
        <div v-if="isImageFile" class="visual-image-wrapper">
          <img :src="previewUrl" :alt="row?.file_name" class="visual-image" />
        </div>
        <!-- PDF 预览 -->
        <div v-else-if="isPdfFile" class="visual-pdf-wrapper">
          <iframe v-if="previewUrl" :src="previewUrl" class="visual-iframe" />
          <div v-else class="visual-fallback">
            <Icon icon="tabler:file-type-pdf" :size="48" style="color: #ef4444" />
            <p>{{ t('PDF preview unavailable') }}</p>
          </div>
        </div>
        <!-- 非预览类型：文件图标 -->
        <div v-else class="visual-icon-wrapper">
          <Icon :icon="fileIcon" :size="56" :style="{ color: fileColor }" />
        </div>
      </div>

      <!-- ② 文件名 + 分类 Badge -->
      <div class="info-identity">
        <div class="info-filename">{{ row?.title || row?.file_name || '—' }}</div>
        <div v-if="row?.title && row?.file_name && row.title !== row.file_name" class="info-subtitle">{{ row.file_name }}</div>
        <div class="info-badges">
          <span v-if="row?.file_type" class="badge-type" :style="{ backgroundColor: fileColor + '18', color: fileColor }">{{ row.file_type.toUpperCase() }}</span>
          <span v-if="row?.file_size" class="badge-size">{{ formatFileSize(row.file_size) }}</span>
          <span v-if="row?.is_private" class="badge-private">
            <Icon icon="tabler:lock" :size="12" />
            {{ t('Private') }}
          </span>
        </div>
      </div>

      <!-- ③ 描述（如果有） -->
      <div v-if="row?.description" class="info-description">
        {{ row.description }}
      </div>

      <!-- ④ 元信息 -->
      <div class="info-section">
        <div class="meta-row" v-if="row?.file_url">
          <span class="meta-icon"><Icon icon="tabler:link" :size="14" /></span>
          <span class="meta-label">{{ t('File URL') }}</span>
          <span class="meta-value meta-url" :title="row.file_url">{{ row.file_url }}</span>
        </div>
        <div class="meta-row" v-if="row?.folder">
          <span class="meta-icon"><Icon icon="tabler:folder" :size="14" /></span>
          <span class="meta-label">{{ t('Folder') }}</span>
          <span class="meta-value">{{ row.folder }}</span>
        </div>
        <div class="meta-row" v-if="attachedToLabel">
          <span class="meta-icon"><Icon icon="tabler:paperclip" :size="14" /></span>
          <span class="meta-label">{{ t('Attached To') }}</span>
          <span class="meta-value">{{ attachedToLabel }}</span>
        </div>
        <div class="meta-row" v-if="row?.content_hash">
          <span class="meta-icon"><Icon icon="tabler:hash" :size="14" /></span>
          <span class="meta-label">{{ t('Content Hash') }}</span>
          <span class="meta-value meta-hash" :title="row.content_hash">{{ row.content_hash }}</span>
        </div>
      </div>

      <!-- ⑤ 时间戳 -->
      <div class="info-section">
        <div class="meta-row" v-if="row?.creation">
          <span class="meta-icon"><Icon icon="tabler:calendar-plus" :size="14" /></span>
          <span class="meta-label">{{ t('Created') }}</span>
          <span class="meta-value">{{ formatDateTime(row.creation) }}</span>
        </div>
        <div class="meta-row" v-if="row?.owner">
          <span class="meta-icon"><Icon icon="tabler:user" :size="14" /></span>
          <span class="meta-label">{{ t('Owner') }}</span>
          <span class="meta-value">{{ row.owner }}</span>
        </div>
        <div class="meta-row" v-if="row?.modified">
          <span class="meta-icon"><Icon icon="tabler:calendar-stats" :size="14" /></span>
          <span class="meta-label">{{ t('Modified') }}</span>
          <span class="meta-value">{{ formatDateTime(row.modified) }}</span>
        </div>
        <div class="meta-row" v-if="row?.modified_by">
          <span class="meta-icon"><Icon icon="tabler-user-edit" :size="14" /></span>
          <span class="meta-label">{{ t('Modified By') }}</span>
          <span class="meta-value">{{ row.modified_by }}</span>
        </div>
      </div>
    </div>

    <!-- ⑥ 底部操作栏 -->
    <div class="preview-actions">
      <button class="action-btn action-primary" @click="$emit('download', row)" :title="t('Download')">
        <Icon icon="tabler:download" :size="16" />
        <span>{{ t('Download') }}</span>
      </button>
      <button class="action-btn action-danger" @click="$emit('delete', row)" :title="t('Delete')">
        <Icon icon="tabler:trash" :size="16" />
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { Icon } from '@iconify/vue'
import { t } from '@/shared/i18n'

const props = defineProps<{
  row: any | null
}>()

defineEmits(['close', 'download', 'delete'])

const IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico']

const isImageFile = computed(() => IMAGE_EXTENSIONS.includes((props.row?.file_type || '').toLowerCase()))
const isPdfFile = computed(() => (props.row?.file_type || '').toLowerCase() === 'pdf')

const previewUrl = computed(() => {
  if (!props.row) return ''
  return props.row.thumbnail_url || props.row.file_url || ''
})

// 文件图标
const fileIcon = computed(() => {
  const ext = (props.row?.file_type || '').toLowerCase()
  if (IMAGE_EXTENSIONS.includes(ext)) return 'tabler:photo'
  if (ext === 'pdf') return 'tabler:file-type-pdf'
  if (['doc', 'docx'].includes(ext)) return 'tabler:file-type-doc'
  if (['xls', 'xlsx'].includes(ext)) return 'tabler:file-type-xls'
  if (['zip', 'rar', '7z'].includes(ext)) return 'tabler:file-zip'
  if (['mp4', 'avi', 'mov'].includes(ext)) return 'tabler:file-type-video'
  if (['mp3', 'wav', 'flac'].includes(ext)) return 'tabler:file-type-audio'
  return 'tabler:file'
})

// 标题栏图标（更小版本）
const headerIcon = computed(() => {
  if (props.row?.is_folder) return 'tabler:folder'
  return fileIcon.value
})

// 文件颜色
const fileColor = computed(() => {
  const ext = (props.row?.file_type || '').toLowerCase()
  if (IMAGE_EXTENSIONS.includes(ext)) return '#10b981'
  if (ext === 'pdf') return '#ef4444'
  if (['doc', 'docx'].includes(ext)) return '#3b82f6'
  if (['xls', 'xlsx'].includes(ext)) return '#059669'
  if (['zip', 'rar', '7z'].includes(ext)) return '#8b5cf6'
  if (['mp4', 'avi', 'mov'].includes(ext)) return '#ec4899'
  if (['mp3', 'wav', 'flac'].includes(ext)) return '#f97316'
  return '#6b7280'
})

// 关联引用标签
const attachedToLabel = computed(() => {
  const pg = props.row?.attached_to_pagetype
  const name = props.row?.attached_to_name
  if (!pg && !name) return ''
  if (pg && name) return `${pg} / ${name}`
  return pg || name || ''
})

function formatFileSize(bytes: number | string): string {
  const size = typeof bytes === 'string' ? parseInt(bytes, 10) : bytes
  if (isNaN(size) || size === 0) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(size) / Math.log(1024))
  return (size / Math.pow(1024, i)).toFixed(i > 0 ? 1 : 0) + ' ' + units[i]
}

import { formatDateTimeInTimezone } from '@/shared/utils/timezone'

function formatDateTime(value: any): string {
  if (!value) return '—'
  try {
    return formatDateTimeInTimezone(value)
  } catch { return String(value) }
}
</script>

<style scoped>
.file-preview-panel {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #fff;
}

/* ===== 标题栏 ===== */
.preview-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0 8px 0 12px;
  height: 45px;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
  flex-shrink: 0;
}

.preview-title {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #1f2937;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
  min-width: 0;
}

.close-btn {
  width: 28px;
  height: 28px;
  border: none;
  border-radius: 6px;
  background: transparent;
  color: #6b7280;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  transition: all 0.15s;
}

.close-btn:hover { background: #fee2e2; color: #dc2626; }

/* ===== 滚动区域 ===== */
.preview-body {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  overflow-x: hidden;
}

/* ===== ① 主预览区 ===== */
.preview-visual {
  background: #f8fafc;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 180px;
  overflow: hidden;
  border-bottom: 1px solid #f0f0f0;
}

.preview-visual:has(.visual-pdf-wrapper) {
  min-height: 400px;
}

.visual-image-wrapper {
  width: 100%;
  max-height: 50vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px;
}

.visual-image {
  max-width: 100%;
  max-height: 50vh;
  object-fit: contain;
  border-radius: 4px;
}

.visual-pdf-wrapper {
  width: 100%;
  flex: 1;
  min-height: 400px;
}

.visual-iframe {
  width: 100%;
  height: 100%;
  min-height: 400px;
  border: none;
}

.visual-fallback {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: #9ca3af;
  font-size: 13px;
}

.visual-icon-wrapper {
  padding: 32px 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* ===== ② 文件名 + Badge ===== */
.info-identity {
  padding: 16px 16px 0;
}

.info-filename {
  font-size: 16px;
  font-weight: 700;
  color: #111827;
  word-break: break-all;
  line-height: 1.4;
}

.info-subtitle {
  font-size: 12px;
  color: #9ca3af;
  margin-top: 2px;
  word-break: break-all;
}

.info-badges {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 6px;
  margin-top: 8px;
}

.badge-type {
  padding: 2px 8px;
  border-radius: 4px;
  font-weight: 700;
  font-size: 11px;
  letter-spacing: 0.5px;
}

.badge-size {
  background: #f3f4f6;
  color: #6b7280;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 11px;
  font-weight: 500;
}

.badge-private {
  display: inline-flex;
  align-items: center;
  gap: 3px;
  background: #fef3c7;
  color: #92400e;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 11px;
  font-weight: 500;
}

/* ===== ③ 描述 ===== */
.info-description {
  margin: 12px 16px 0;
  padding: 10px 12px;
  background: #f8fafc;
  border-radius: 6px;
  font-size: 13px;
  color: #4b5563;
  line-height: 1.5;
  word-break: break-word;
}

/* ===== ④⑤ 元信息 / 时间戳 ===== */
.info-section {
  padding: 12px 16px 0;
}

.info-section + .info-section {
  border-top: 1px solid #f3f4f6;
  padding-top: 12px;
  margin-top: 12px;
}

.meta-row {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 4px 0;
  font-size: 13px;
  line-height: 1.5;
}

.meta-icon {
  flex-shrink: 0;
  color: #9ca3af;
  display: flex;
  align-items: center;
}

.meta-label {
  color: #6b7280;
  flex-shrink: 0;
  min-width: 80px;
}

.meta-value {
  color: #374151;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.meta-hash {
  font-family: 'SF Mono', 'Fira Code', 'Cascadia Code', monospace;
  font-size: 12px;
  color: #9ca3af;
}

.meta-url {
  font-family: 'SF Mono', 'Fira Code', 'Cascadia Code', monospace;
  font-size: 12px;
  color: #6b7280;
}

/* 底部间距 */
.preview-body > :last-child {
  padding-bottom: 16px;
}

/* ===== ⑥ 操作栏 ===== */
.preview-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0 16px;
  height: 47px;
  border-top: 1px solid #f0f0f0;
  flex-shrink: 0;
  background: #fff;
}

.action-btn {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  padding: 6px 14px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  background: #fff;
  color: #374151;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.15s;
}

.action-btn:hover { background: #f3f4f6; border-color: #d1d5db; }

.action-primary {
  background: #f8fafc;
  color: #3b82f6;
  border-color: #bfdbfe;
}

.action-primary:hover {
  background: #eff6ff;
  border-color: #93c5fd;
}

.action-danger {
  margin-left: auto;
  color: #6b7280;
}

.action-danger:hover {
  background: #fee2e2;
  color: #dc2626;
  border-color: #fecaca;
}
</style>
