<template>
  <section class="doc-card" :class="{ 'is-collapsed': collapsedState }">
    <header class="doc-card__header">
      <div class="doc-card__badge">{{ typeLabel }}</div>
      <div class="doc-card__meta">
        <div class="doc-card__name">{{ docName }}</div>
        <div class="doc-card__time">{{ displayTime }}</div>
      </div>
      <div class="doc-card__actions">
        <button type="button" class="doc-card__btn" :title="collapsedState ? '展开文件' : '折叠文件'" @click="toggleCollapse">
          <svg v-if="collapsedState" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <polyline points="9 18 15 12 9 6"/>
          </svg>
          <svg v-else width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <polyline points="6 9 12 15 18 9"/>
          </svg>
        </button>
        <button type="button" class="doc-card__btn doc-card__btn--danger" title="删除文件" @click="props.onDelete?.()">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M3 6h18"/>
            <path d="M8 6V4h8v2"/>
            <path d="M19 6l-1 14H6L5 6"/>
            <path d="M10 11v6"/>
            <path d="M14 11v6"/>
          </svg>
        </button>
      </div>
    </header>
    <div v-show="!collapsedState" class="doc-card__body">
      <div ref="editorRoot" class="doc-card__editor"></div>
    </div>
  </section>
</template>

<script setup>
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { replaceAll } from '@milkdown/kit/utils'
import { Crepe } from '@milkdown/crepe'
import { editorViewCtx } from '@milkdown/kit/core'
import { copilotPlugin, copilotConfigCtx, copilotGhostMark, setCopilotEnabled, clearGhostSuggestion } from '../plugins/copilotPlugin'
import { fetchSuggestion } from '../utils/api.js'

const props = defineProps({
  docType: { type: String, default: 'txt' },
  docName: { type: String, default: 'document.txt' },
  uploadTime: { type: String, default: '' },
  content: { type: String, default: '' },
  collapsed: { type: Boolean, default: false },
  resolveSuggestionRequest: { type: Function, default: null },
  onUpdateContent: { type: Function, default: null },
  onUpdateCollapsed: { type: Function, default: null },
  onDelete: { type: Function, default: null },
})

const editorRoot = ref(null)
const collapsedState = ref(Boolean(props.collapsed))
const currentContent = ref(props.content || '')
let crepe = null
let syncTimer = null
let syncingExternal = false

const typeLabel = computed(() => {
  if (props.docType === 'docx') return 'DOCX'
  if (props.docType === 'pptx') return 'PPTX'
  if (props.docType === 'pdf') return 'PDF'
  return 'TXT'
})

const displayTime = computed(() => {
  if (!props.uploadTime) return '刚上传'
  const date = new Date(props.uploadTime)
  if (Number.isNaN(date.getTime())) return '刚上传'
  return date.toLocaleString('zh-CN', { hour12: false })
})

const toggleCollapse = () => {
  collapsedState.value = !collapsedState.value
  props.onUpdateCollapsed?.(collapsedState.value)
}

const syncContent = () => {
  if (!crepe) return
  if (syncTimer) clearTimeout(syncTimer)
  syncTimer = setTimeout(async () => {
    if (!crepe || syncingExternal) return
    const markdown = await crepe.getMarkdown()
    currentContent.value = markdown
    props.onUpdateContent?.(markdown)
  }, 120)
}

const syncExternalContent = async (nextValue) => {
  const value = nextValue || ''
  if (!crepe) {
    currentContent.value = value
    return
  }
  if (value === currentContent.value) return
  syncingExternal = true
  try {
    crepe.editor.action(replaceAll(value))
    currentContent.value = value
  } finally {
    syncingExternal = false
  }
}

watch(() => props.content, (nextValue) => {
  void syncExternalContent(nextValue)
})

watch(() => props.collapsed, (nextValue) => {
  collapsedState.value = Boolean(nextValue)
})

onMounted(async () => {
  if (!editorRoot.value) return
  crepe = new Crepe({
    root: editorRoot.value,
    defaultValue: props.content || '',
    features: {
      [Crepe.Feature.Latex]: true,
      [Crepe.Feature.ImageBlock]: true,
      [Crepe.Feature.Table]: true,
      [Crepe.Feature.ListCheck]: true,
    },
    config: {
      showLineNumber: false,
    },
  })

  crepe.editor.config((ctx) => {
    ctx.set(copilotConfigCtx.key, {
      fetchSuggestion: async (prefix, suffix, languageId, signal) => {
        const payload = props.resolveSuggestionRequest
          ? await props.resolveSuggestionRequest({ prefix, suffix, languageId })
          : { prefix, suffix, languageId, blocked: false }
        if (payload?.blocked) return ''
        return fetchSuggestion(payload?.prefix ?? prefix, payload?.suffix ?? suffix, payload?.languageId ?? languageId, signal)
      },
      debounceMs: 900,
    })
  })

  crepe.editor.use(copilotConfigCtx)
  crepe.editor.use(copilotGhostMark)
  crepe.editor.use(copilotPlugin)
  await crepe.create()

  crepe.on((listener) => {
    listener.updated(() => {
      syncContent()
    })
  })

  crepe.editor.action((ctx) => {
    const view = ctx.get(editorViewCtx)
    setCopilotEnabled(view, true)
  })
})

onUnmounted(() => {
  if (syncTimer) {
    clearTimeout(syncTimer)
    syncTimer = null
  }
  if (crepe) {
    crepe.editor.action((ctx) => {
      const view = ctx.get(editorViewCtx)
      clearGhostSuggestion(view)
    })
    crepe.destroy()
    crepe = null
  }
})
</script>

<style scoped>
.doc-card {
  width: 100%;
  max-width: 100%;
  margin: 8px 0;
  border-radius: 12px;
  border: 1px solid rgba(59, 130, 246, 0.12);
  background: rgba(255, 255, 255, 0.78);
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.06), 0 1px 3px rgba(0, 0, 0, 0.04);
  overflow: hidden;
  backdrop-filter: blur(10px);
  position: relative;
}

.doc-card__header {
  display: grid;
  grid-template-columns: auto minmax(0, 1fr) auto;
  gap: 10px;
  align-items: center;
  padding: 8px 12px;
  border-bottom: 1px solid rgba(59, 130, 246, 0.1);
  background: rgba(255, 255, 255, 0.6);
}

.doc-card__badge {
  min-width: 48px;
  padding: 4px 10px;
  border-radius: 999px;
  background: linear-gradient(135deg, #3b82f6 0%, #60a5fa 100%);
  color: #fff;
  font-size: 10px;
  font-weight: 600;
  letter-spacing: 0.08em;
  text-align: center;
  box-shadow: 0 2px 6px rgba(59, 130, 246, 0.2);
}

.doc-card__meta {
  min-width: 0;
}

.doc-card__name {
  color: #1e293b;
  font-size: 13px;
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.doc-card__time {
  margin-top: 2px;
  color: #64748b;
  font-size: 10px;
}

.doc-card__actions {
  display: flex;
  gap: 4px;
}

.doc-card__btn {
  width: 26px;
  height: 26px;
  border: 1px solid rgba(59, 130, 246, 0.12);
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.5);
  color: #64748b;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.15s ease;
}

.doc-card__btn:hover {
  background: rgba(59, 130, 246, 0.1);
  border-color: rgba(59, 130, 246, 0.25);
  color: #3b82f6;
}

.doc-card__btn--danger:hover {
  background: rgba(239, 68, 68, 0.1);
  border-color: rgba(239, 68, 68, 0.2);
  color: #ef4444;
}

.doc-card__body {
  padding: 8px 10px;
  background: rgba(248, 250, 252, 0.5);
}

.doc-card__editor {
  min-height: 48px;
  border-radius: 8px;
  border: 1px solid rgba(59, 130, 246, 0.08);
  background: rgba(255, 255, 255, 0.6);
  overflow: hidden;
}

.doc-card__editor :deep(.milkdown) {
  background: transparent !important;
}

.doc-card__editor :deep(.milkdown__main),
.doc-card__editor :deep(.milkdown__editor) {
  margin: 0 !important;
  padding: 0 !important;
}

.doc-card__editor :deep(.ProseMirror) {
  min-height: 0;
  padding: 10px 12px 12px !important;
  font-size: 13px !important;
  line-height: 1.6;
}

.doc-card__editor :deep(.ProseMirror > *:last-child) {
  margin-bottom: 0;
}

.doc-card__editor :deep(.ProseMirror p:first-child) {
  margin-top: 0;
}

.doc-card__editor :deep(.milkdown__toolbar),
.doc-card__editor :deep(.milkdown__menu),
.doc-card__editor :deep(.milkdown__statusbar),
.doc-card__editor :deep(.milkdown-slate-toolbar),
.doc-card__editor :deep(.milkdown-bubble-menu) {
  display: none !important;
}
</style>

