<template>
  <NModal
    :show="show"
    preset="card"
    :title="`保存为${PHASE_TITLE[phase]}产物`"
    class="max-w-4xl"
    @update:show="(v: boolean) => emit('update:show', v)"
  >
    <div class="space-y-3">
      <NTabs type="segment">
        <NTabPane name="edit" tab="编辑">
          <NInput
            v-model:value="content"
            type="textarea"
            placeholder="产物内容（Markdown，可在保存前修改）"
            :autosize="{ minRows: 12, maxRows: 24 }"
          />
        </NTabPane>
        <NTabPane name="preview" tab="预览">
          <!-- eslint-disable vue/no-v-html -->
          <div
            class="prose prose-sm max-w-none max-h-[60vh] overflow-y-auto border rounded p-3"
            v-html="rendered"
          />
          <!-- eslint-enable vue/no-v-html -->
        </NTabPane>
      </NTabs>
      <NInput v-model:value="note" placeholder="版本备注（可选）" />
      <div class="flex justify-end gap-2">
        <NButton @click="emit('update:show', false)"> 取消 </NButton>
        <NButton type="primary" :loading="saving" :disabled="!content.trim()" @click="onSave">
          保存为新版本
        </NButton>
      </div>
    </div>
  </NModal>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { NButton, NInput, NModal, NTabPane, NTabs, useMessage } from 'naive-ui'

import type { ArtifactPhase } from '@/api/projects'
import type { ChatMessage } from '@/api/chat'
import { md } from '@/utils/markdown'
import { useRequirementsStore } from '@/stores/requirements'

const PHASE_TITLE: Record<ArtifactPhase, string> = {
  planning: '规划',
  prototyping: '原型',
  auditing: '评审',
}

const props = defineProps<{
  show: boolean
  slug: string
  number: number
  phase: ArtifactPhase
  sourceMessage: ChatMessage | null
}>()

const emit = defineEmits<{ 'update:show': [v: boolean]; saved: [] }>()

const store = useRequirementsStore()
const message = useMessage()

const content = ref('')
const note = ref('')
const saving = ref(false)

const rendered = computed(() => md.render(content.value))

// 每次打开时从来源消息初始化可编辑内容。
watch(
  () => props.show,
  (v) => {
    if (v) {
      content.value = props.sourceMessage?.content ?? ''
      note.value = ''
    }
  },
)

async function onSave() {
  if (!content.value.trim()) return
  saving.value = true
  try {
    await store.createArtifact(props.slug, props.number, {
      phase: props.phase,
      content: content.value,
      note: note.value || undefined,
      source_message_id: props.sourceMessage?.id,
    })
    message.success('已保存为新版本')
    emit('update:show', false)
    emit('saved')
  } catch (e) {
    message.error(e instanceof Error ? e.message : '保存失败')
  } finally {
    saving.value = false
  }
}
</script>
