<template>
  <div class="code-preview">
    <div class="preview-header">
      <div class="preview-header-left">
        <el-icon><Document /></el-icon>
        <span class="preview-filename">{{ schema.fileName }}</span>
        <el-tag size="small" type="info">{{ schema.format.toUpperCase() }}</el-tag>
      </div>
      <div class="preview-header-actions">
        <el-button-group>
          <el-tooltip content="复制到剪贴板" placement="top">
            <el-button :icon="CopyDocument" @click="handleCopy" />
          </el-tooltip>
          <el-tooltip content="下载文件" placement="top">
            <el-button :icon="Download" @click="handleDownload" />
          </el-tooltip>
        </el-button-group>
      </div>
    </div>
    <div ref="editorContainer" class="editor-container"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { CopyDocument, Download } from '@element-plus/icons-vue'
import * as monaco from 'monaco-editor'
import { getLanguage } from '../schemas'

const props = defineProps({
  code: { type: String, default: '' },
  schema: { type: Object, required: true },
})

const editorContainer = ref(null)
let editor = null

// Monaco editor theme
function defineTheme() {
  monaco.editor.defineTheme('confTheme', {
    base: 'vs',
    inherit: true,
    rules: [
      { token: 'comment', foreground: '6a737d', fontStyle: 'italic' },
      { token: 'keyword', foreground: 'd73a49' },
      { token: 'string', foreground: '032f62' },
      { token: 'number', foreground: '005cc5' },
      { token: 'type', foreground: '6f42c1' },
      { token: 'delimiter', foreground: '24292e' },
    ],
    colors: {
      'editor.background': '#fafbfc',
      'editor.lineHighlightBackground': '#f6f8fa',
      'editorLineNumber.foreground': '#bfc3c8',
      'editorLineNumber.activeForeground': '#24292e',
      'editorGutter.background': '#fafbfc',
      'editor.inactiveSelectionBackground': '#28a74520',
      'editor.selectionBackground': '#28a74530',
    },
  })
}

onMounted(async () => {
  defineTheme()

  editor = monaco.editor.create(editorContainer.value, {
    value: props.code,
    language: getLanguage(props.schema.format),
    theme: 'confTheme',
    readOnly: true,
    minimap: { enabled: false },
    scrollBeyondLastLine: false,
    lineNumbers: 'on',
    renderLineHighlight: 'line',
    fontSize: 13,
    lineHeight: 20,
    fontFamily: "'JetBrains Mono', 'Fira Code', 'SF Mono', 'Cascadia Code', Consolas, monospace",
    padding: { top: 12, bottom: 12 },
    scrollbar: {
      verticalScrollbarSize: 8,
      horizontalScrollbarSize: 8,
    },
    overviewRulerLanes: 0,
    hideCursorInOverviewRuler: true,
    overviewRulerBorder: false,
    wordWrap: 'on',
    automaticLayout: true,
  })
})

watch(
  () => props.code,
  (newCode) => {
    if (editor) {
      const model = editor.getModel()
      if (model) {
        monaco.editor.setModelLanguage(model, getLanguage(props.schema.format))
        model.setValue(newCode)
      }
    }
  },
)

watch(
  () => props.schema.format,
  (newFormat) => {
    if (editor) {
      const model = editor.getModel()
      if (model) {
        monaco.editor.setModelLanguage(model, getLanguage(newFormat))
      }
    }
  },
)

onBeforeUnmount(() => {
  if (editor) {
    editor.dispose()
  }
})

async function handleCopy() {
  try {
    await navigator.clipboard.writeText(props.code)
    ElMessage.success('已复制到剪贴板')
  } catch {
    // Fallback
    const textarea = document.createElement('textarea')
    textarea.value = props.code
    document.body.appendChild(textarea)
    textarea.select()
    document.execCommand('copy')
    document.body.removeChild(textarea)
    ElMessage.success('已复制到剪贴板')
  }
}

function handleDownload() {
  const blob = new Blob([props.code], { type: 'text/plain;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = props.schema.fileName
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
  ElMessage.success(`已下载 ${props.schema.fileName}`)
}
</script>

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

.preview-header {
  padding: 10px 16px;
  background: #fff;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-shrink: 0;
}

.preview-header-left {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #303133;
}

.preview-filename {
  font-size: 13px;
  font-weight: 600;
  font-family: 'JetBrains Mono', 'Fira Code', monospace;
}

.preview-header-actions .el-button-group .el-button {
  border-color: #dcdfe6;
}

.editor-container {
  flex: 1;
  min-height: 0;
}
</style>
