<template>
  <div style="max-width: 1100px">
    <n-breadcrumb style="margin-bottom: 16px">
      <n-breadcrumb-item @click="navigateTo('/admin/blogs')">博客文章</n-breadcrumb-item>
      <n-breadcrumb-item>{{ isNew ? '新增' : '编辑' }}</n-breadcrumb-item>
    </n-breadcrumb>

    <n-space justify="space-between" align="center" style="margin-bottom: 24px">
      <h1 style="margin: 0; font-size: 20px; font-weight: 600; color: #111827">{{ isNew ? '新增博客' : '编辑博客' }}</h1>
      <n-space>
        <n-button secondary @click="navigateTo('/admin/blogs')">取消</n-button>
        <n-button type="primary" :loading="saving" @click="handleSave">保存</n-button>
      </n-space>
    </n-space>

    <n-card v-if="loadError" style="text-align: center; color: #ef4444">{{ loadError }}</n-card>
    <n-spin v-else-if="pageLoading" style="display: flex; justify-content: center; padding: 60px" />

    <template v-else>
      <div class="form-layout">
        <div class="form-main">
          <n-card title="基本信息">
            <n-form label-placement="top">
              <n-form-item label="标题" required>
                <n-input v-model:value="form.title" placeholder="输入博客标题" />
              </n-form-item>
              <n-form-item label="Slug" required>
                <n-input v-model:value="form.slug" placeholder="如 hulunbuir-travel-guide" />
                <template #feedback>用于生成博客链接</template>
              </n-form-item>
              <n-form-item label="摘要">
                <n-input v-model:value="form.summary" type="textarea" :rows="3" placeholder="简要描述" />
              </n-form-item>
              <n-form-item label="正文（支持 HTML）">
                <n-input v-model:value="form.content" type="textarea" :rows="20" placeholder="输入博客正文" />
              </n-form-item>
            </n-form>
          </n-card>

          <n-card title="SEO 设置" style="margin-top: 16px">
            <n-form label-placement="top">
              <n-form-item label="SEO 标题">
                <n-input v-model:value="form.seoTitle" placeholder="留空则使用文章标题" />
              </n-form-item>
              <n-form-item label="SEO 描述">
                <n-input v-model:value="form.seoDesc" type="textarea" :rows="2" placeholder="搜索引擎描述" />
              </n-form-item>
              <n-form-item label="SEO 关键词">
                <n-input v-model:value="form.seoKeywords" placeholder="逗号分隔" />
              </n-form-item>
            </n-form>
          </n-card>
        </div>

        <div class="form-sidebar">
          <n-card title="发布设置">
            <n-form label-placement="top">
              <n-form-item label="状态">
                <n-select v-model:value="form.published" :options="[{ label: '已发布', value: true }, { label: '草稿', value: false }]" />
              </n-form-item>
              <n-form-item label="分类">
                <n-select v-model:value="form.category" :options="[{ label: '攻略', value: '攻略' }, { label: '亲子', value: '亲子' }, { label: '游记', value: '游记' }]" />
              </n-form-item>
              <n-form-item label="作者">
                <n-input v-model:value="form.author" />
              </n-form-item>
            </n-form>
          </n-card>

          <n-card title="封面图">
            <AdminImageUpload v-model="form.coverImage" />
          </n-card>
        </div>
      </div>

      <n-alert v-if="formError" type="error" style="margin-top: 12px">{{ formError }}</n-alert>

      <div class="save-bar">
        <n-button secondary @click="navigateTo('/admin/blogs')">取消</n-button>
        <n-button type="primary" :loading="saving" @click="handleSave">保存</n-button>
      </div>
    </template>
  </div>
</template>

<script setup>
import { NButton, NCard, NSpace, NInput, NForm, NFormItem, NSelect, NBreadcrumb, NBreadcrumbItem, NSpin, NAlert } from 'naive-ui'
import { useMessage } from 'naive-ui'

definePageMeta({ layout: 'admin', middleware: 'admin' })

const route = useRoute()
const { adminFetch } = useAdmin()
const message = useMessage()

const isNew = computed(() => route.params.id === 'new')
const pageLoading = ref(!isNew.value)
const loadError = ref('')
const saving = ref(false)
const formError = ref('')

const form = ref({
  title: '', slug: '', category: '攻略', author: '呼籁旅行',
  summary: '', content: '', coverImage: '',
  seoTitle: '', seoDesc: '', seoKeywords: '', published: true,
})

async function loadItem() {
  if (isNew.value) return
  pageLoading.value = true
  try {
    const d = await adminFetch(`/api/admin/articles/${route.params.id}`)
    form.value = { ...d, published: !!d.published, coverImage: d.coverImage || '' }
  } catch (e) { loadError.value = e.data?.message || '加载失败' }
  finally { pageLoading.value = false }
}

async function handleSave() {
  if (!form.value.title?.trim() || !form.value.slug?.trim()) { formError.value = '标题和 Slug 不能为空'; return }
  saving.value = true; formError.value = ''
  try {
    if (isNew.value) {
      await adminFetch('/api/admin/articles', { method: 'POST', body: { ...form.value, type: 'blog' } })
      message.success('创建成功')
      setTimeout(() => navigateTo('/admin/blogs'), 800)
    } else {
      await adminFetch(`/api/admin/articles/${route.params.id}`, { method: 'PUT', body: form.value })
      message.success('保存成功')
    }
  } catch (e) { formError.value = e.data?.message || '保存失败' }
  finally { saving.value = false }
}

onMounted(loadItem)
</script>

<style scoped>
.form-layout { display: grid; grid-template-columns: 1fr 300px; gap: 20px; align-items: start; }
.form-main { min-width: 0; }
.form-sidebar { display: flex; flex-direction: column; gap: 16px; }
.save-bar { position: sticky; bottom: 0; display: flex; justify-content: flex-end; gap: 8px; padding: 16px 0; margin-top: 24px; background: #f0f2f5; border-top: 1px solid #e5e7eb; }
</style>
