<template>
  <Teleport to="body">
    <div
      v-if="isOpen"
      class="fixed inset-0 z-[9998] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4"
      @click.self="emit('close')"
    >
      <div class="w-full max-w-6xl max-h-[90vh] bg-[#121214] border border-white/10 rounded-xl shadow-2xl flex flex-col overflow-hidden">
        <div class="flex items-center justify-between px-6 py-4 border-b border-white/10 shrink-0">
          <div>
            <h3 class="text-lg font-medium text-white">历史版本</h3>
            <p class="text-xs text-art-muted mt-1">每次保存后生成新版本，vN 表示第 N 次保存后的内容</p>
          </div>
          <button type="button" class="text-art-muted hover:text-white" @click="emit('close')">✕</button>
        </div>

        <div class="flex items-center gap-3 px-6 py-3 border-b border-white/10 shrink-0 bg-white/[0.02]">
          <button
            type="button"
            class="admin-btn-primary text-xs"
            :disabled="!activeVersion"
            @click="restoreVersion(activeVersion!)"
          >
            恢复此版本
          </button>
          <span v-if="activeVersion" class="text-xs text-art-muted">当前查看：v{{ activeVersion }}</span>
          <span v-else class="text-xs text-art-muted">请从左侧选择一个版本</span>
        </div>

        <div class="flex-1 overflow-hidden flex min-h-0">
          <!-- 左侧版本列表 -->
          <div class="w-72 border-r border-white/10 overflow-y-auto custom-scrollbar shrink-0">
            <div v-if="loading" class="p-6 text-center text-art-muted text-sm">加载中...</div>
            <div v-else-if="historyList.length === 0" class="p-6 text-center text-art-muted text-sm">暂无历史版本</div>
            <button
              v-for="item in historyList"
              :key="item.version"
              type="button"
              class="w-full text-left px-4 py-3 border-b border-white/5 hover:bg-white/5 transition-colors"
              :class="{ 'bg-art-accent/10 border-l-2 border-l-art-accent': activeVersion === item.version }"
              @click="selectVersion(item.version)"
            >
              <div class="flex items-center justify-between gap-2">
                <span class="text-sm text-white font-medium">v{{ item.version }}</span>
                <span class="text-xs text-art-muted">{{ item.modifiedAt }}</span>
              </div>
              <AuthorInfo
                class="mt-2"
                :name="item.userName || item.modifiedByName"
                :email="item.userEmail"
                :avatar="item.userAvatar"
                :user-id="item.userId || item.modifiedBy"
                variant="compact"
                size="sm"
              />
              <p class="text-xs text-white/70 mt-0.5 truncate">{{ item.title }}</p>
            </button>
          </div>

          <!-- 右侧 Tab 面板 -->
          <div class="flex-1 flex flex-col min-h-0 overflow-hidden">
            <div v-if="!activeVersion" class="flex-1 flex items-center justify-center text-sm text-art-muted">
              点击左侧版本查看内容与变更对比
            </div>

            <div v-else-if="detailLoading" class="flex-1 flex items-center justify-center text-sm text-art-muted">
              加载版本详情...
            </div>

            <template v-else-if="previewData">
              <!-- 主 Tab 栏 -->
              <div class="flex border-b border-white/10 shrink-0">
                <button
                  type="button"
                  class="px-5 py-2.5 text-sm transition-colors"
                  :class="activeMainTab === 'preview'
                    ? 'text-art-accent bg-white/5 border-b-2 border-art-accent'
                    : 'text-white/40 hover:text-white/70'"
                  @click="activeMainTab = 'preview'"
                >
                  版本内容
                </button>
                <button
                  type="button"
                  class="px-5 py-2.5 text-sm transition-colors flex items-center gap-2"
                  :class="activeMainTab === 'diff'
                    ? 'text-art-accent bg-white/5 border-b-2 border-art-accent'
                    : 'text-white/40 hover:text-white/70'"
                  :disabled="activeVersion === 1"
                  @click="activeMainTab = 'diff'"
                >
                  变更对比
                  <span
                    v-if="changedCount > 0"
                    class="text-[10px] px-1.5 py-0.5 rounded-full bg-art-accent/20 text-art-accent font-medium"
                  >
                    {{ changedCount }}
                  </span>
                </button>
              </div>

              <!-- Tab: 版本内容 -->
              <div
                v-show="activeMainTab === 'preview'"
                class="flex-1 flex flex-col min-h-0 overflow-hidden"
              >
                <div class="flex-1 overflow-y-auto custom-scrollbar p-6 flex flex-col min-h-0">
                  <div class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-3 text-sm shrink-0 mb-4">
                    <div class="md:col-span-2">
                      <span class="text-art-muted">标题：</span>
                      <span class="text-white">{{ previewData.title }}</span>
                    </div>
                    <div>
                      <span class="text-art-muted">分类：</span>
                      <span class="text-white">{{ previewData.categoryName || '—' }}</span>
                    </div>
                    <div>
                      <span class="text-art-muted">专栏：</span>
                      <span class="text-white">{{ previewData.columnName || '—' }}</span>
                    </div>
                    <div>
                      <span class="text-art-muted">标签：</span>
                      <span class="text-white">{{ previewData.tagNames?.join(', ') || '—' }}</span>
                    </div>
                    <div>
                      <span class="text-art-muted">状态：</span>
                      <span class="text-white">{{ previewData.isPublished === 1 ? '已发布' : '草稿' }}</span>
                    </div>
                    <div class="flex items-start gap-2 md:col-span-2">
                      <span class="text-art-muted shrink-0">操作人：</span>
                      <AuthorInfo
                        :name="previewData.userName || previewData.modifiedByName"
                        :email="previewData.userEmail"
                        :avatar="previewData.userAvatar"
                        :user-id="previewData.userId || previewData.modifiedBy"
                        variant="compact"
                        size="sm"
                      />
                    </div>
                    <div class="md:col-span-2">
                      <span class="text-art-muted">摘要：</span>
                      <span class="text-white">{{ previewData.excerpt || '—' }}</span>
                    </div>
                  </div>

                  <div class="flex-1 flex flex-col min-h-0">
                    <span class="text-art-muted text-sm mb-2 shrink-0">正文</span>
                    <div class="flex-1 min-h-[200px] bg-black/30 rounded-lg p-4 overflow-y-auto custom-scrollbar prose prose-invert prose-sm max-w-none">
                      <MdPreview :model-value="previewData.content || ''" theme="dark" />
                    </div>
                  </div>
                </div>
              </div>

              <!-- Tab: 变更对比 -->
              <div
                v-show="activeMainTab === 'diff'"
                class="flex-1 flex flex-col min-h-0 overflow-hidden"
              >
                <!-- v1 empty state -->
                <div
                  v-if="activeVersion === 1"
                  class="flex-1 flex items-center justify-center p-6"
                >
                  <div class="text-sm text-art-muted rounded-lg border border-white/10 p-6 bg-white/[0.02] text-center max-w-md">
                    这是首个版本，无上一版本可对比
                  </div>
                </div>

                <template v-else-if="diffData">
                  <!-- 摘要条 -->
                  <div class="px-6 py-3 border-b border-white/10 shrink-0 bg-white/[0.02] flex items-center gap-3">
                    <span class="text-sm text-white">
                      v{{ diffData.fromVersion }} → v{{ diffData.toVersion }}
                    </span>
                    <span
                      v-if="changedCount > 0"
                      class="text-xs px-2 py-0.5 rounded-full bg-art-accent/15 text-art-accent"
                    >
                      {{ changedCount }} 项变更
                    </span>
                    <span v-else class="text-xs text-art-muted">无变更</span>
                  </div>

                  <!-- 无变更 empty state -->
                  <div
                    v-if="changedCount === 0"
                    class="flex-1 flex items-center justify-center p-6"
                  >
                    <div class="text-sm text-art-muted rounded-lg border border-white/10 p-6 bg-white/[0.02] text-center max-w-md">
                      与上一版本相比，所有字段均无变化
                    </div>
                  </div>

                  <template v-else>
                    <!-- 字段子 Tab -->
                    <div class="flex gap-1 px-4 py-2 border-b border-white/10 shrink-0 overflow-x-auto custom-scrollbar">
                      <button
                        v-for="[key] in changedFields"
                        :key="key"
                        type="button"
                        class="shrink-0 px-3 py-1.5 text-xs rounded-md transition-colors"
                        :class="activeDiffField === key
                          ? 'bg-art-accent/15 text-art-accent border border-art-accent/30'
                          : 'text-white/50 hover:text-white/80 hover:bg-white/5 border border-transparent'"
                        @click="activeDiffField = key"
                      >
                        {{ fieldLabel(key) }}
                      </button>
                    </div>

                    <!-- 双栏对比 -->
                    <div
                      v-if="activeDiffFieldData"
                      class="flex-1 flex flex-col md:flex-row min-h-0 overflow-hidden"
                    >
                      <!-- 旧版 -->
                      <div class="flex-1 flex flex-col min-h-0 md:border-r border-white/10">
                        <div class="px-4 py-2 text-xs text-art-muted border-b border-white/5 shrink-0 bg-black/20">
                          旧版 v{{ diffData.fromVersion }}
                        </div>
                        <div class="flex-1 overflow-y-auto custom-scrollbar p-4 min-h-0">
                          <template v-if="activeDiffField === 'content'">
                            <div class="prose prose-invert prose-sm max-w-none">
                              <MdPreview :model-value="activeDiffFieldData.from || ''" theme="dark" />
                            </div>
                          </template>
                          <p v-else class="text-sm text-white/80 whitespace-pre-wrap break-words">
                            {{ activeDiffFieldData.from || '—' }}
                          </p>
                        </div>
                      </div>

                      <!-- 新版 -->
                      <div class="flex-1 flex flex-col min-h-0">
                        <div class="px-4 py-2 text-xs text-art-muted border-b border-white/5 shrink-0 bg-art-accent/5">
                          新版 v{{ diffData.toVersion }}
                        </div>
                        <div class="flex-1 overflow-y-auto custom-scrollbar p-4 min-h-0">
                          <template v-if="activeDiffField === 'content'">
                            <div class="prose prose-invert prose-sm max-w-none">
                              <MdPreview :model-value="activeDiffFieldData.to || ''" theme="dark" />
                            </div>
                          </template>
                          <p v-else class="text-sm text-white/80 whitespace-pre-wrap break-words">
                            {{ activeDiffFieldData.to || '—' }}
                          </p>
                        </div>
                      </div>
                    </div>

                    <!-- 无变化字段折叠区 -->
                    <div v-if="unchangedCount > 0" class="shrink-0 border-t border-white/10">
                      <button
                        type="button"
                        class="w-full px-6 py-2.5 text-xs text-art-muted hover:text-white/70 hover:bg-white/[0.02] transition-colors flex items-center gap-2"
                        @click="showUnchanged = !showUnchanged"
                      >
                        <span>{{ showUnchanged ? '收起' : '展开' }}</span>
                        <span>{{ unchangedCount }} 项无变化</span>
                        <span class="ml-auto">{{ showUnchanged ? '▲' : '▼' }}</span>
                      </button>
                      <div v-if="showUnchanged" class="px-6 pb-4 flex flex-wrap gap-2">
                        <span
                          v-for="[key] in unchangedFields"
                          :key="key"
                          class="text-xs px-2 py-1 rounded bg-white/[0.03] border border-white/5 text-art-muted"
                        >
                          {{ fieldLabel(key) }}
                        </span>
                      </div>
                    </div>
                  </template>
                </template>
              </div>
            </template>
          </div>
        </div>
      </div>
    </div>
  </Teleport>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { MdPreview } from 'md-editor-v3'
import 'md-editor-v3/lib/preview.css'
import {
  getPostHistory,
  getPostHistoryByVersion,
  getPostHistoryDiff,
  restorePostHistory,
  type PostHistory,
  type PostHistoryDiff,
  type PostHistoryFieldDiff
} from '../../services/api'
import { useToast } from '../../composables/useToast'
import AuthorInfo from '../AuthorInfo.vue'

const FIELD_LABELS: Record<string, string> = {
  title: '标题',
  excerpt: '摘要',
  content: '正文',
  category: '分类',
  column: '专栏',
  tags: '标签',
  isPublished: '发布状态'
}

const props = defineProps<{
  isOpen: boolean
  postId: number | string
}>()

const emit = defineEmits<{
  close: []
  restored: []
}>()

const toast = useToast()
const loading = ref(false)
const detailLoading = ref(false)
const historyList = ref<PostHistory[]>([])
const activeVersion = ref<number | null>(null)
const previewData = ref<PostHistory | null>(null)
const diffData = ref<PostHistoryDiff | null>(null)
const activeMainTab = ref<'preview' | 'diff'>('preview')
const activeDiffField = ref<string | null>(null)
const showUnchanged = ref(false)

const fieldLabel = (key: string | number) => FIELD_LABELS[String(key)] || String(key)

const changedFields = computed(() =>
  Object.entries(diffData.value?.fields ?? {}).filter(([, f]) => f.changed)
)

const unchangedFields = computed(() =>
  Object.entries(diffData.value?.fields ?? {}).filter(([, f]) => !f.changed)
)

const changedCount = computed(() => changedFields.value.length)

const unchangedCount = computed(() => unchangedFields.value.length)

const activeDiffFieldData = computed((): PostHistoryFieldDiff | null => {
  if (!activeDiffField.value || !diffData.value) return null
  return diffData.value.fields[activeDiffField.value] ?? null
})

const applyTabDefaults = (version: number) => {
  if (version > 1 && changedCount.value > 0) {
    activeMainTab.value = 'diff'
    activeDiffField.value = changedFields.value[0]?.[0] ?? null
  } else {
    activeMainTab.value = 'preview'
    activeDiffField.value = null
  }
  showUnchanged.value = false
}

const loadHistory = async () => {
  if (!props.postId) return
  loading.value = true
  try {
    historyList.value = await getPostHistory(props.postId)
    historyList.value.sort((a, b) => b.version - a.version)
    if (historyList.value.length > 0) {
      await selectVersion(historyList.value[0].version)
    }
  } catch (error: any) {
    toast.showToast(error.message || '加载历史版本失败', 'error')
  } finally {
    loading.value = false
  }
}

const selectVersion = async (version: number) => {
  activeVersion.value = version
  detailLoading.value = true
  previewData.value = null
  diffData.value = null
  try {
    const [detail, diff] = await Promise.all([
      getPostHistoryByVersion(props.postId, version),
      version > 1 ? getPostHistoryDiff(props.postId, version - 1, version) : Promise.resolve(null)
    ])
    previewData.value = detail
    diffData.value = diff
    applyTabDefaults(version)
  } catch (error: any) {
    toast.showToast(error.message || '加载版本详情失败', 'error')
  } finally {
    detailLoading.value = false
  }
}

const restoreVersion = async (version: number) => {
  if (!confirm(`确定将文章恢复为版本 v${version} 吗？当前内容会先保存为新版本。`)) return
  try {
    await restorePostHistory(props.postId, version)
    toast.showToast('版本恢复成功', 'success')
    emit('restored')
    emit('close')
  } catch (error: any) {
    toast.showToast(error.message || '恢复失败', 'error')
  }
}

watch(
  () => props.isOpen,
  (open) => {
    if (open) {
      activeVersion.value = null
      previewData.value = null
      diffData.value = null
      activeMainTab.value = 'preview'
      activeDiffField.value = null
      showUnchanged.value = false
      loadHistory()
    }
  }
)
</script>

<style scoped>
.custom-scrollbar::-webkit-scrollbar { width: 4px; height: 4px; }
.custom-scrollbar::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.1); border-radius: 2px; }
</style>
