<template>
  <div class="w-full animate-reveal h-[calc(100vh-8rem)] flex flex-col">
    <!-- Top Bar -->
    <div class="flex items-center justify-between mb-4 shrink-0">
      <div class="flex items-center gap-4">
        <h1 class="text-2xl font-serif italic text-white">{{ isEditing ? '编辑专栏' : '新建专栏' }}</h1>
      </div>
      <div class="flex gap-3">
        <button type="button" class="admin-btn-secondary" @click="handleCancel">
          取消
        </button>
        <button type="button" class="admin-btn-primary" @click="handleSubmit" :disabled="isSubmitting">
          {{ isSubmitting ? '提交中...' : (isEditing ? '保存修改' : '创建专栏') }}
        </button>
      </div>
    </div>

    <div class="admin-card p-6 max-w-2xl mx-auto w-full">
      <form @submit.prevent="handleSubmit" class="space-y-6">
        <!-- Name Field -->
        <div class="space-y-2">
          <label for="name" class="block text-xs font-medium text-art-muted uppercase tracking-wider">名称</label>
          <input
              type="text"
              id="name"
              v-model="form.name"
              class="admin-input"
              placeholder="请输入专栏名称"
              required
          />
        </div>

        <!-- Cover Field -->
        <div class="space-y-2">
          <label for="cover" class="block text-xs font-medium text-art-muted uppercase tracking-wider">封面图片</label>
          <ImageUpload 
            v-model="form.cover"
            :category-id="1"
          />
        </div>

        <!-- Status Field -->
        <div class="space-y-2">
          <label class="block text-xs font-medium text-art-muted uppercase tracking-wider">状态</label>
          <div class="flex gap-4 mt-2">
            <label class="flex items-center cursor-pointer">
              <input type="radio" v-model="form.isActive" :value="1" class="mr-2">
              <span class="text-sm text-white">启用</span>
            </label>
            <label class="flex items-center cursor-pointer">
              <input type="radio" v-model="form.isActive" :value="0" class="mr-2">
              <span class="text-sm text-white">禁用</span>
            </label>
          </div>
        </div>

        <!-- Sort Order Field -->
        <div class="space-y-2">
          <label for="sortOrder" class="block text-xs font-medium text-art-muted uppercase tracking-wider">排序 (越小越靠前)</label>
          <input
              type="number"
              id="sortOrder"
              v-model="form.sortOrder"
              class="admin-input"
              placeholder="0"
          />
        </div>

        <!-- Description Field -->
        <div class="space-y-2">
          <label for="description" class="block text-xs font-medium text-art-muted uppercase tracking-wider">描述</label>
          <textarea
              id="description"
              v-model="form.description"
              rows="4"
              class="admin-input resize-none"
              placeholder="简短的专栏描述..."
          ></textarea>
        </div>

        <!-- Post Management Section (Only in Edit Mode) -->
        <div v-if="isEditing" class="pt-6 border-t border-white/10">
          <h3 class="text-lg font-medium text-white mb-4">文章管理</h3>
          
          <!-- Add Post -->
          <div class="flex gap-2 mb-6">
            <div class="flex-1">
              <CustomSelect
                v-model="selectedPostId"
                :options="postOptions"
                placeholder="选择文章添加到专栏..."
              />
            </div>
            <button type="button" @click="handleAddPost" class="admin-btn-secondary whitespace-nowrap" :disabled="!selectedPostId || selectedPostId === 0">
              添加文章
            </button>
          </div>

          <!-- Post List -->
          <div class="space-y-2">
            <label class="block text-xs font-medium text-art-muted uppercase tracking-wider">已关联文章 ({{ columnPosts.length }})</label>
            <div v-if="columnPosts.length > 0" class="border border-white/10 rounded-lg divide-y divide-white/5 bg-white/5">
              <div v-for="post in columnPosts" :key="post.id" class="flex items-center justify-between p-3">
                <span class="text-sm text-white">{{ post.title }}</span>
                <button type="button" @click="handleRemovePost(post.id)" class="text-red-400 hover:text-red-300 text-xs px-2 py-1">
                  移除
                </button>
              </div>
            </div>
            <div v-else class="text-center py-8 text-art-muted text-sm border border-dashed border-white/10 rounded-lg">
              暂无关联文章
            </div>
          </div>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useToast } from '../../composables/useToast'
import { createColumn, updateColumn, fetchColumn, fetchPosts, fetchColumnPosts, addPostToColumn, removePostFromColumn, Post } from '../../services/api'
import CustomSelect from '../../components/CustomSelect.vue'
import ImageUpload from '../../components/admin/ImageUpload.vue'

const router = useRouter()
const route = useRoute()
const toast = useToast()

const isSubmitting = ref(false)
const isEditing = computed(() => !!route.params.id)

const form = reactive({
  name: '',
  cover: '',
  description: '',
  isActive: 1,
  sortOrder: 0
})

const allPosts = ref<Post[]>([])
const columnPosts = ref<Post[]>([])
const selectedPostId = ref<number | string>(0)

// 计算属性：文章选项
const postOptions = computed(() => {
  return [
    { value: 0, label: '选择文章添加到专栏...' },
    ...allPosts.value.map(post => ({
      value: post.id,
      label: `${post.title} (${post.isPublished ? '已发布' : '草稿'})`
    }))
  ]
})

const handleSubmit = async () => {
  if (!form.name.trim()) {
    toast.showToast('名称不能为空', 'error')
    return
  }

  isSubmitting.value = true

  try {
    if (isEditing.value) {
      const id = parseInt(route.params.id as string)
      await updateColumn(id, form)
      toast.showToast('专栏更新成功', 'success')
    } else {
      await createColumn(form)
      toast.showToast('专栏创建成功', 'success')
    }
    router.push('/admin/columns')
  } catch (error: any) {
    console.error('Error submitting form:', error)
    toast.showToast(error.message || (isEditing.value ? '更新专栏失败' : '创建专栏失败'), 'error')
  } finally {
    isSubmitting.value = false
  }
}

const handleCancel = () => {
  router.back()
}

const loadPosts = async () => {
  try {
    const response = await fetchPosts()
    // fetchPosts 现在返回 PaginationResponse<Post>，需要取 .list
    allPosts.value = 'list' in response ? response.list : []
  } catch (error) {
    console.error('Failed to load posts:', error)
  }
}

const loadColumnPosts = async () => {
  if (!isEditing.value) return
  try {
    const id = parseInt(route.params.id as string)
    const posts = await fetchColumnPosts(id)
    columnPosts.value = posts
  } catch (error) {
    console.error('Failed to load column posts:', error)
  }
}

const handleAddPost = async () => {
  if (!selectedPostId.value || selectedPostId.value === 0) return
  if (!isEditing.value) return

  try {
    const id = parseInt(route.params.id as string)
    const postId = typeof selectedPostId.value === 'string' ? parseInt(selectedPostId.value) : selectedPostId.value
    await addPostToColumn(id, postId)
    toast.showToast('文章添加成功', 'success')
    selectedPostId.value = 0
    await loadColumnPosts()
    await loadPosts() // 重新加载以更新选项
  } catch (error: any) {
    toast.showToast(error.message || '添加文章失败', 'error')
  }
}

const handleRemovePost = async (postId: number) => {
  if (!isEditing.value) return

  try {
    const id = parseInt(route.params.id as string)
    await removePostFromColumn(id, postId)
    toast.showToast('文章移除成功', 'success')
    await loadColumnPosts()
    await loadPosts() // 重新加载以更新选项
  } catch (error: any) {
    toast.showToast(error.message || '移除文章失败', 'error')
  }
}

onMounted(async () => {
  if (isEditing.value) {
    try {
      const id = parseInt(route.params.id as string)
      const column = await fetchColumn(id)
      if (column) {
        form.name = column.name
        form.cover = column.cover
        form.description = column.description
        form.isActive = column.isActive
        form.sortOrder = column.sortOrder
      }
      await loadColumnPosts()
    } catch (error) {
      console.error('Failed to load column:', error)
      toast.showToast('加载数据失败', 'error')
    }
  }
  await loadPosts()
})
</script>
