<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>
        <button 
          type="button" 
          @click="toggleSidebar"
          class="p-2 rounded-md hover:bg-white/5 text-art-muted hover:text-white transition-colors border border-transparent hover:border-white/10"
          :title="isSidebarOpen ? '收起侧边栏' : '展开侧边栏'"
        >
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="transition-transform duration-300" :class="{ 'rotate-180': !isSidebarOpen }">
            <rect width="18" height="18" x="3" y="3" rx="2" ry="2"></rect>
            <line x1="15" x2="15" y1="3" y2="21"></line>
          </svg>
        </button>
      </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>

    <form @submit.prevent="handleSubmit" class="flex-1 flex overflow-hidden gap-6 relative">
      <!-- Left Column: Main Editor -->
      <div class="flex-1 flex flex-col min-w-0 transition-all duration-300 ease-in-out h-full">
        <div class="admin-card flex-1 flex flex-col overflow-hidden border border-white/10 focus-within:border-art-accent/50 transition-colors">
          <MdEditor
              v-model="form.content"
              theme="dark"
              :preview="false"
              placeholder="开始创作..."
              class="custom-md-editor flex-1"
          />
        </div>
      </div>
      
      <!-- Right Column: Meta & Settings (Collapsible) -->
      <div 
        class="shrink-0 transition-all duration-300 ease-[cubic-bezier(0.25,0.8,0.25,1)] overflow-hidden flex flex-col h-full"
        :class="[isSidebarOpen ? 'w-80 opacity-100 translate-x-0' : 'w-0 opacity-0 translate-x-10']"
      >
        <div class="w-80 space-y-6 overflow-y-auto pr-1 h-full custom-scrollbar pb-6">
          <div class="admin-card p-6 space-y-6">
            <h3 class="text-sm font-medium text-white border-b border-white/5 pb-4 mb-4 flex items-center gap-2">
              <span class="text-art-accent">📝</span> 文章属性
            </h3>

            <!-- Title Field -->
            <div class="space-y-2">
              <label for="title" class="block text-xs font-medium text-art-muted uppercase tracking-wider">文章标题</label>
              <input
                  type="text"
                  id="title"
                  v-model="form.title"
                  class="admin-input font-medium"
                  placeholder="请输入标题"
                  required
              />
              <div class="text-art-error text-xs mt-1" v-if="errors.title">
                {{ errors.title }}
              </div>
            </div>

            <!-- Excerpt Field -->
            <div class="space-y-2">
              <label for="excerpt" class="block text-xs font-medium text-art-muted uppercase tracking-wider">摘要</label>
              <textarea
                  id="excerpt"
                  v-model="form.excerpt"
                  rows="4"
                  class="admin-input resize-none text-sm leading-relaxed"
                  placeholder="简短的介绍..."
              ></textarea>
              <div class="text-art-error text-xs mt-1" v-if="errors.excerpt">
                {{ errors.excerpt }}
              </div>
            </div>
             
            <!-- Category Field -->
            <div class="space-y-2">
              <label for="category" class="block text-xs font-medium text-art-muted uppercase tracking-wider">分类</label>
              <CustomSelect
                  v-model="form.categoryId"
                  :options="categories"
                  placeholder="选择文章分类"
              />
              <div class="text-art-error text-xs mt-1" v-if="errors.categoryId">
                {{ errors.categoryId }}
              </div>
            </div>
            
            <!-- Tags Field -->
            <div class="space-y-2">
              <label class="block text-xs font-medium text-art-muted uppercase tracking-wider">标签</label>
              <div class="flex flex-wrap gap-2">
                <button
                  type="button"
                  v-for="tag in availableTags"
                  :key="tag.id"
                  @click="toggleTag(tag.id)"
                  class="px-2 py-1 text-xs rounded border transition-colors"
                  :class="form.tagIds.includes(tag.id) ? 'bg-art-accent/20 border-art-accent text-art-accent' : 'bg-white/5 border-white/10 text-art-muted hover:border-white/30'"
                >
                  {{ tag.name }}
                </button>
                <div v-if="availableTags.length === 0" class="text-xs text-art-muted italic">
                  暂无可用标签
                </div>
              </div>
            </div>
            
            <!-- Date Field -->
            <div class="space-y-2">
              <label for="date" class="block text-xs font-medium text-art-muted uppercase tracking-wider">发布日期</label>
              <input
                  type="date"
                  id="date"
                  v-model="form.date"
                  class="admin-input"
                  required
              />
              <div class="text-art-error text-xs mt-1" v-if="errors.date">
                {{ errors.date }}
              </div>
            </div>
            
            <!-- Is Published Field -->
            <div class="space-y-2">
              <label for="isPublished" class="block text-xs font-medium text-art-muted uppercase tracking-wider">状态</label>
              <CustomSelect
                  v-model="form.isPublished"
                  :options="publishStatusOptions"
                  placeholder="请选择发布状态"
              />
              <div class="text-art-error text-xs mt-1" v-if="errors.isPublished">
                {{ errors.isPublished }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
// 引入 md-editor-v3
import { MdEditor } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'

import { useToast } from '../../composables/useToast'
import { createPost, updatePost, fetchPost, fetchCategories, fetchTags, Category, Tag } from '../../services/api'
import CustomSelect from '../../components/CustomSelect.vue'

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

// Sidebar toggle state
const isSidebarOpen = ref(true)
const toggleSidebar = () => {
  isSidebarOpen.value = !isSidebarOpen.value
}

// Form state
const isSubmitting = ref(false)
const isEditing = computed(() => !!route.params.id)
const errors = reactive<Record<string, string>>({})

// Data sources
const categories = ref<{value: number, label: string}[]>([])
const availableTags = ref<Tag[]>([])

// Form data
const form = reactive({
  title: '',
  categoryId: 0,
  date: new Date().toISOString().split('T')[0],
  excerpt: '',
  content: '',
  isPublished: 1,
  tagIds: [] as number[]
})

// Select options
const publishStatusOptions = [
  { value: 1, label: '已发布' },
  { value: 0, label: '草稿' }
]

// Validation function
const validateForm = (): boolean => {
  // Reset errors
  Object.keys(errors).forEach(key => delete errors[key])

  let isValid = true

  // Validate title
  if (!form.title.trim()) {
    errors.title = '文章标题不能为空'
    isValid = false
    // Auto open sidebar if there are errors in it
    isSidebarOpen.value = true
  }

  // Validate category
  if (!form.categoryId) {
    errors.categoryId = '请选择文章分类'
    isValid = false
    isSidebarOpen.value = true
  }

  // Validate date
  if (!form.date) {
    errors.date = '发布日期不能为空'
    isValid = false
    isSidebarOpen.value = true
  }

  // Validate content
  if (!form.content.trim()) {
    errors.content = '文章内容不能为空'
    isValid = false
  }

  return isValid
}

// Toggle tag selection
const toggleTag = (tagId: number) => {
  const index = form.tagIds.indexOf(tagId)
  if (index === -1) {
    form.tagIds.push(tagId)
  } else {
    form.tagIds.splice(index, 1)
  }
}

// Submit handler
const handleSubmit = async () => {
  if (!validateForm()) {
    return
  }

  isSubmitting.value = true

  try {
    // Construct payload
    const payload = {
      title: form.title,
      categoryId: form.categoryId,
      date: form.date,
      excerpt: form.excerpt,
      content: form.content,
      isPublished: form.isPublished,
      tags: form.tagIds.map(id => ({ id } as any)) // Backend expects objects with ID
    }

    if (isEditing.value) {
      // Update existing post
      await updatePost(route.params.id as string, payload)
      toast.showToast('文章更新成功', 'success')
    } else {
      // Create new post
      await createPost(payload)
      toast.showToast('文章创建成功', 'success')
    }

    // Redirect to posts list
    router.push('/admin/posts')
  } catch (error: any) {
    console.error('Error submitting form:', error)
    toast.showToast(error.message || (isEditing.value ? '更新文章失败' : '创建文章失败'), 'error')
  } finally {
    isSubmitting.value = false
  }
}

// Cancel handler
const handleCancel = () => {
  router.push('/admin/posts')
}

// Load initial data
const loadData = async () => {
  try {
    // Fetch categories and tags in parallel
    const [cats, tags] = await Promise.all([
      fetchCategories(),
      fetchTags()
    ])
    
    categories.value = cats.map(c => ({
      value: c.id,
      label: c.name
    }))
    
    availableTags.value = tags

    // If editing, load post data
    if (isEditing.value) {
      const postId = route.params.id as string
      const post = await fetchPost(postId)

      // Populate form with post data
      form.title = post.title
      form.categoryId = post.categoryId
      form.date = post.date
      form.excerpt = post.excerpt || ''
      form.content = post.content || ''
      form.isPublished = post.isPublished === 1 ? 1 : 0
      
      // Map tags to tagIds
      if (post.tags && post.tags.length > 0) {
        form.tagIds = post.tags.map(t => t.id)
      }
    }
  } catch (error: any) {
    console.error('Failed to load data:', error)
    toast.showToast('加载数据失败: ' + (error.message || '未知错误'), 'error')
  }
}

// Lifecycle
onMounted(() => {
  loadData()
})
</script>

<style scoped>
:deep(.custom-md-editor) {
  background-color: transparent !important;
  --md-bk-color: transparent !important;
  --md-color: white !important;
  --md-border-color: transparent !important;
  height: 100% !important;
}

:deep(.md-editor-toolbar-wrapper) {
  background-color: rgba(255, 255, 255, 0.02) !important;
  border-bottom: 1px solid rgba(255, 255, 255, 0.05) !important;
  padding: 4px 8px;
}

:deep(.md-editor-content) {
  background-color: transparent !important;
}

:deep(.md-editor-footer) {
  background-color: rgba(255, 255, 255, 0.02) !important;
  border-top: 1px solid rgba(255, 255, 255, 0.05) !important;
}

/* Custom Scrollbar for sidebar */
.custom-scrollbar::-webkit-scrollbar {
  width: 4px;
}
.custom-scrollbar::-webkit-scrollbar-track {
  background: transparent;
}
.custom-scrollbar::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 2px;
}
.custom-scrollbar:hover::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
}
</style>
