<template>
  <NCard :title="`${PHASE_TITLE[phase]}产物`">
    <div class="flex gap-4">
      <!-- 版本列表 -->
      <div class="w-44 shrink-0">
        <NList v-if="artifacts.length > 0" :show-divider="false">
          <NListItem v-for="a in artifacts" :key="a.id">
            <NThing class="cursor-pointer" @click="selectedVersion = a.version">
              <template #header>
                <span
                  class="text-sm font-medium"
                  :class="selectedVersion === a.version ? 'text-blue-600' : ''"
                  >v{{ a.version }}</span
                >
                <NTag v-if="a.source_message_id" size="tiny" class="ml-1"> AI </NTag>
              </template>
              <template #header-extra>
                <span class="text-xs text-gray-400">
                  {{ new Date(a.created_at).toLocaleDateString() }}
                </span>
              </template>
              <span v-if="a.note" class="text-xs text-gray-500">{{ a.note }}</span>
            </NThing>
          </NListItem>
        </NList>
        <NEmpty v-else description="暂无产物版本" size="small" />
      </div>

      <!-- 选中版本内容（markdown 渲染） -->
      <div class="flex-1 min-w-0">
        <!-- eslint-disable vue/no-v-html -->
        <div v-if="selectedArtifact" class="prose prose-sm max-w-none" v-html="rendered" />
        <!-- eslint-enable vue/no-v-html -->
        <p v-else class="text-gray-400 text-sm">选择左侧版本以查看内容</p>
      </div>
    </div>

    <!-- 手动提交新版本 -->
    <NDivider />
    <div v-if="!readonly" class="space-y-2">
      <NInput
        v-model:value="newContent"
        type="textarea"
        placeholder="产物内容（Markdown）"
        :autosize="{ minRows: 3, maxRows: 10 }"
      />
      <NInput v-model:value="newNote" placeholder="备注（可选）" />
      <NButton
        type="primary"
        size="small"
        :loading="submitting"
        :disabled="!newContent.trim()"
        @click="onSubmit"
      >
        提交新版本
      </NButton>
    </div>
    <p v-else class="text-gray-400 text-sm">需求已关闭，无法提交新版本</p>
  </NCard>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { NButton, NCard, NDivider, NEmpty, NInput, NList, NListItem, NTag, NThing } from 'naive-ui'
import type { Artifact, ArtifactPhase } from '@/api/projects'
import { md } from '@/utils/markdown'
import { useRequirementsStore } from '@/stores/requirements'

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

const props = defineProps<{
  slug: string
  number: number
  phase: ArtifactPhase
  readonly?: boolean
}>()

const store = useRequirementsStore()

const artifacts = ref<Artifact[]>([])
const selectedVersion = ref<number | null>(null)
const newContent = ref('')
const newNote = ref('')
const submitting = ref(false)

const selectedArtifact = computed(
  () => artifacts.value.find((a) => a.version === selectedVersion.value) ?? null,
)
const rendered = computed(() =>
  selectedArtifact.value ? md.render(selectedArtifact.value.content) : '',
)

// latest 暴露给父组件：创建会话时把当前阶段或上一阶段最新版注入 system prompt。
const latest = computed(() =>
  artifacts.value.length > 0 ? artifacts.value[artifacts.value.length - 1] : null,
)

async function refresh() {
  artifacts.value = await store.listArtifacts(props.slug, props.number, props.phase)
  if (artifacts.value.length > 0) {
    if (selectedVersion.value === null || !selectedArtifact.value) {
      selectedVersion.value = artifacts.value[artifacts.value.length - 1].version
    }
  } else {
    selectedVersion.value = null
  }
}

async function onSubmit() {
  if (!newContent.value.trim()) return
  submitting.value = true
  try {
    const created = await store.createArtifact(props.slug, props.number, {
      phase: props.phase,
      content: newContent.value,
      note: newNote.value || undefined,
    })
    newContent.value = ''
    newNote.value = ''
    selectedVersion.value = created.version
    await refresh()
  } finally {
    submitting.value = false
  }
}

// 阶段切换时重载该阶段产物（选中状态重置）
watch(
  () => props.phase,
  () => {
    selectedVersion.value = null
    refresh()
  },
)

onMounted(refresh)

defineExpose({ refresh, latest })
</script>
