<script setup lang="ts">
import { request, unwrapApiBody, type ApiResponse } from '../../../utils/http/factory'

definePageMeta({ title: '新建文章' })

const state = reactive({
  title: '',
  slug: '',
  excerpt: '',
  bodyMarkdown: '',
  visibility: 'private',
})
const loading = ref(false)

async function submit() {
  loading.value = true
  try {
    const res = await request<ApiResponse<{ post: { id: number } }>>('/api/me/posts', {
      method: 'POST',
      body: {
        title: state.title,
        slug: state.slug,
        excerpt: state.excerpt,
        bodyMarkdown: state.bodyMarkdown,
        visibility: state.visibility,
      },
    })
    const id = unwrapApiBody(res).post.id
    await navigateTo(`/me/posts/${id}`)
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <UContainer class="py-8 max-w-3xl space-y-4">
    <h1 class="text-2xl font-semibold">
      新建文章
    </h1>
    <UForm :state="state" class="space-y-4" @submit.prevent="submit">
      <UFormField label="标题" name="title" required>
        <UInput v-model="state.title" />
      </UFormField>
      <UFormField label="slug" name="slug" required>
        <UInput v-model="state.slug" />
      </UFormField>
      <UFormField label="摘要" name="excerpt" required>
        <UInput v-model="state.excerpt" />
      </UFormField>
      <UFormField label="正文 Markdown" name="bodyMarkdown" required>
        <UTextarea v-model="state.bodyMarkdown" :rows="16" class="w-full font-mono text-sm" />
      </UFormField>
      <UFormField label="可见性" name="visibility">
        <USelect
          v-model="state.visibility"
          :items="[
            { label: '私密', value: 'private' },
            { label: '公开', value: 'public' },
            { label: '仅链接', value: 'unlisted' },
          ]"
        />
      </UFormField>
      <div class="flex gap-2">
        <UButton type="submit" :loading="loading">
          创建
        </UButton>
        <UButton to="/me/posts" variant="ghost" color="neutral">
          返回
        </UButton>
      </div>
    </UForm>
  </UContainer>
</template>
