<script setup lang="ts">
import type MarkdownIt from 'markdown-it'
import { MdEditor } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import { attachMarkdownItStripFrontMatter } from '../utils/markdown-front-matter'

const props = defineProps<{
  modelValue: string
}>()

const emit = defineEmits<{
  'update:modelValue': [string]
}>()

const { fetchData } = useClientApi()
const toast = useToast()
const editorId = `post-body-md-${useId()}`
const previewFmRule = `strip_fm_${useId().replace(/[^a-zA-Z0-9_]/g, '_')}`

function markdownItConfig(md: MarkdownIt) {
  attachMarkdownItStripFrontMatter(md, previewFmRule)
}

const local = computed({
  get: () => props.modelValue,
  set: (v: string) => emit('update:modelValue', v),
})

async function onUploadImg(files: File[], callback: (urls: string[]) => void) {
  const form = new FormData()
  for (const f of files) {
    form.append('file', f)
  }
  try {
    const { files: uploaded } = await fetchData<{ files: { url: string }[] }>('/api/file/upload', {
      method: 'POST',
      body: form,
    })
    toast.add({ title: '图片已上传', color: 'success' })
    callback(uploaded.map((x) => x.url))
  } catch {
    callback([])
  }
}
</script>

<template>
  <ClientOnly>
    <MdEditor
      :id="editorId"
      v-model="local"
      language="zh-CN"
      :preview="true"
      preview-theme="github"
      theme="light"
      :markdown-it-config="markdownItConfig"
      :on-upload-img="onUploadImg"
      :style="{ height: 'min(72vh, 720px)' }"
      class="w-full rounded-lg overflow-hidden ring ring-default"
    />
    <template #fallback>
      <div class="text-muted text-sm py-12 text-center border border-default rounded-lg">
        编辑器加载中…
      </div>
    </template>
  </ClientOnly>
</template>
