<template>
  <div>
    <h1 class="text-2xl font-bold mb-6">编辑文章</h1>

    <div v-if="loading" class="space-y-4">
      <USkeleton class="h-10" />
      <USkeleton class="h-10" />
      <USkeleton class="h-96" />
    </div>

    <div v-else-if="!article" class="text-center py-16">
      <p class="text-gray-600">文章不存在</p>
      <UButton to="/" color="indigo" class="mt-4">返回首页</UButton>
    </div>

    <template v-else>
      <UForm :state="form" @submit="onSubmit" class="space-y-6">
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <!-- 编辑区 -->
          <div class="space-y-4">
            <UFormField label="标题" name="title" required>
              <UInput v-model="form.title" placeholder="请输入文章标题" class="w-full" />
            </UFormField>

            <UFormField label="Slug" name="slug">
              <UInput v-model="form.slug" placeholder="自动生成" class="w-full" />
            </UFormField>

            <UFormField label="摘要" name="excerpt">
              <UTextarea v-model="form.excerpt" placeholder="请输入文章摘要（可选）" class="w-full" />
            </UFormField>

            <UFormField label="封面图 URL" name="coverImageUrl">
              <UInput v-model="form.coverImageUrl" placeholder="输入封面图 URL（可选）" class="w-full" />
            </UFormField>

            <MarkdownToolbar @insert="insertMarkdown" />

            <UFormField label="内容" name="content" required>
              <UTextarea
                v-model="form.content"
                :minrows="15"
                :maxrows="30"
                placeholder="在此输入 Markdown 内容..."
                class="w-full font-mono"
                ref="contentRef"
              />
            </UFormField>

            <div class="grid grid-cols-2 gap-4">
              <UFormField label="状态" name="status">
                <USelect v-model="form.status" :options="statusOptions" class="w-full" />
              </UFormField>

              <UFormField label="可见性" name="visibility">
                <USelect v-model="form.visibility" :options="visibilityOptions" class="w-full" />
              </UFormField>
            </div>

            <div class="flex gap-4">
              <UButton type="submit" color="indigo" :loading="saving">
                更新
              </UButton>
              <UButton variant="outline" @click="$router.push(`/article/${article.slug}`)">
                预览
              </UButton>
              <UButton variant="ghost" @click="$router.back()">
                取消
              </UButton>
            </div>
          </div>

          <!-- 预览区 -->
          <div class="space-y-4">
            <h3 class="font-medium text-gray-700 dark:text-gray-300">实时预览</h3>
            <div class="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-4 min-h-[600px] max-h-[800px] overflow-auto">
              <div v-if="form.content" class="prose prose-indigo dark:prose-invert max-w-none" v-html="renderedContent" />
              <div v-else class="text-gray-400 text-center py-12">
                <UIcon name="i-heroicons-eye" class="w-12 h-12 mx-auto mb-4" />
                <p>实时预览内容</p>
              </div>
            </div>
          </div>
        </div>
      </UForm>
    </template>
  </div>
</template>

<script setup lang="ts">
import { marked } from 'marked'

definePageMeta({
  layout: 'default',
  middleware: ['auth'],
})

const route = useRoute()
const router = useRouter()
const { put } = useApi()
const { fetchArticleById } = useArticles()

const articleId = parseInt(route.params.id as string)
const contentRef = ref<HTMLTextAreaElement | null>(null)

const article = ref<any>(null)
const loading = ref(true)
const saving = ref(false)

const form = ref({
  title: '',
  slug: '',
  content: '',
  excerpt: '',
  coverImageUrl: '',
  status: 'draft' as const,
  visibility: 'public' as const,
})

const statusOptions = [
  { label: '草稿', value: 'draft' },
  { label: '已发布', value: 'published' },
  { label: '归档', value: 'archived' },
]

const visibilityOptions = [
  { label: '公开', value: 'public' },
  { label: '未列出', value: 'unlisted' },
  { label: '私密', value: 'private' },
]

const renderedContent = computed(() => {
  return marked.parse(form.value.content || '', { breaks: true, gfm: true })
})

const insertMarkdown = (before: string, after: string) => {
  const textarea = contentRef.value?.querySelector('textarea')
  if (!textarea) return

  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  const text = form.value.content
  const selected = text.substring(start, end)

  form.value.content = text.substring(0, start) + before + selected + after + text.substring(end)

  setTimeout(() => {
    textarea.focus()
    const newCursor = start + before.length + selected.length
    textarea.setSelectionRange(newCursor, newCursor)
  }, 0)
}

const loadArticle = async () => {
  loading.value = true
  try {
    article.value = await fetchArticleById(articleId)
    form.value = {
      title: article.value.title,
      slug: article.value.slug,
      content: article.value.content || '',
      excerpt: article.value.excerpt || '',
      coverImageUrl: article.value.coverImageUrl || '',
      status: article.value.status,
      visibility: article.value.visibility,
    }
  } catch (error) {
    console.error('Failed to load article:', error)
  } finally {
    loading.value = false
  }
}

const onSubmit = async () => {
  if (!form.value.title.trim() || !form.value.content.trim()) return

  saving.value = true
  try {
    const data = { ...form.value }
    if (!data.slug) {
      data.slug = data.title.toLowerCase().replace(/[^\w\s-]/g, '').replace(/\s+/g, '-')
    }

    await put(`/articles/${articleId}`, data)
    router.push(`/article/${data.slug}`)
  } catch (error) {
    console.error('Failed to update article:', error)
  } finally {
    saving.value = false
  }
}

onMounted(() => {
  loadArticle()
})

useSeoMeta({
  title: () => article.value ? `编辑：${article.value.title} - LinkShare Blog` : '编辑文章 - LinkShare Blog',
})
</script>
