<template>
  <div class="max-w-4xl mx-auto px-4 py-8">
    <div v-if="loading" class="flex justify-center py-8">
      <LoadingSpinner text="Loading..." />
    </div>

    <div v-else class="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6">
      <h1 class="text-2xl font-bold mb-6 text-gray-900 dark:text-white">
        {{ isEdit ? 'Edit Post' : 'Create New Post' }}
      </h1>

      <form @submit.prevent="handleSubmit" class="space-y-6">
        <!-- Title -->
        <div>
          <label for="title" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Title</label>
          <input
            type="text"
            id="title"
            v-model="form.title"
            class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white sm:text-sm"
            required
          />
        </div>

        <!-- Category -->
        <div>
          <label for="category" class="block text-sm font-medium text-gray-700 dark:text-gray-300">分类</label>
          <select
            id="category"
            v-model="form.category_id"
            class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white sm:text-sm"
            required
          >
            <option value="">请选择分类</option>
            <option v-for="category in categories" :key="category.id" :value="category.id">
              {{ category.name }}
            </option>
          </select>
        </div>

        <!-- Summary -->
        <div>
          <label for="summary" class="block text-sm font-medium text-gray-700 dark:text-gray-300">摘要</label>
          <textarea
            id="summary"
            v-model="form.summary"
            rows="2"
            class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white sm:text-sm"
            placeholder="请输入帖子摘要（可选）"
          ></textarea>
        </div>

        <!-- Content Editor -->
        <div>
          <label for="content" class="block text-sm font-medium text-gray-700 dark:text-gray-300">内容</label>
          <div class="mt-1">
            <RichTextEditor
              v-model="form.content"
              @blur="() => {}"
            />
          </div>
        </div>

        <!-- Submit Buttons -->
        <div class="flex justify-end space-x-4">
          <button
            type="button"
            @click="$router.back()"
            class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-gray-500"
          >
            Cancel
          </button>
          <button
            type="submit"
            :disabled="submitting"
            class="px-4 py-2 text-sm font-medium text-white bg-green-600 hover:bg-green-700 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {{ submitting ? 'Saving...' : (isEdit ? 'Save' : 'Publish') }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { usePosts } from '../composables/usePosts'
import { useAuth } from '../composables/useAuth'
import { useCategories } from '../composables/useCategories'
import LoadingSpinner from '../components/LoadingSpinner.vue'
import RichTextEditor from '../components/RichTextEditor.vue'

const route = useRoute()
const router = useRouter()
const { currentPost, loading, error, getPost, createPost, updatePost } = usePosts()
const { user } = useAuth()
const { categories, fetchCategories } = useCategories()

const isEdit = computed(() => !!route.params.id)
const submitting = ref(false)

const form = ref({
  title: '',
  content: '',
  category_id: '',
  summary: '',
})

const handleSubmit = async () => {
  if (submitting.value) return
  if (!user.value) {
    router.push('/login')
    return
  }

  submitting.value = true
  try {
    if (isEdit.value) {
      await updatePost(route.params.id, {
        ...form.value,
        author_id: user.value.id
      })
      router.push(`/article/${route.params.id}`)
    } else {
      const post = await createPost({
        ...form.value,
        author_id: user.value.id
      })
      router.push(`/article/${post.id}`)
    }
  } catch (err) {
    console.error('Failed to save post:', err)
  } finally {
    submitting.value = false
  }
}

onMounted(async () => {
  await fetchCategories()
  if (isEdit.value) {
    await getPost(route.params.id)
    if (currentPost.value) {
      form.value = {
        title: currentPost.value.title,
        content: currentPost.value.content,
        category_id: currentPost.value.category_id,
        summary: currentPost.value.summary || '',
      }
    }
  }
})
</script>
