<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 
          v-if="isEditing" 
          type="button" 
          class="admin-btn-secondary" 
          @click="openHistoryModal"
          title="查看历史版本"
        >
          📜 历史版本
        </button>
        <button 
          v-if="isEditing" 
          type="button" 
          class="admin-btn-secondary" 
          @click="openAccessLogModal"
          title="查看访问记录"
        >
          📊 访问记录
        </button>
        <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"
          @paste="handleVideoPaste"
        >
          <MdEditor
              ref="editorRef"
              v-model="form.content"
              theme="dark"
              :preview="false"
              placeholder="开始创作..."
              class="custom-md-editor flex-1"
              @onUploadImg="handleUploadImg"
              @onDrop="handleEditorDrop"
          />
        </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">
              <div class="flex items-center justify-between">
                <label for="category" class="block text-xs font-medium text-art-muted uppercase tracking-wider">分类</label>
                <button 
                  type="button"
                  @click="showCreateCategory = true" 
                  class="text-xs text-art-accent hover:text-white transition-colors"
                >
                  + 新建分类
                </button>
              </div>
              <CustomSelect
                  v-model="form.categoryId"
                  :options="categories"
                  placeholder="选择文章分类"
              />
              <div class="text-art-error text-xs mt-1" v-if="errors.categoryId">
                {{ errors.categoryId }}
              </div>
              
              <!-- Quick Create Category -->
              <div v-if="showCreateCategory" class="admin-card p-3 space-y-2 mt-2">
                <input
                  v-model="newCategory.name"
                  placeholder="分类名称"
                  class="admin-input text-sm"
                  @keyup.enter="createCategory"
                />
                <div class="flex gap-2">
                  <button type="button" @click="createCategory" class="admin-btn-primary text-xs px-3 py-1">创建</button>
                  <button type="button" @click="showCreateCategory = false" class="admin-btn-secondary text-xs px-3 py-1">取消</button>
                </div>
              </div>
            </div>
            
            <!-- Column Field -->
            <div class="space-y-2">
              <div class="flex items-center justify-between">
                <label for="column" class="block text-xs font-medium text-art-muted uppercase tracking-wider">专栏 <span class="text-art-muted text-xs">(可选)</span></label>
                <button 
                  type="button"
                  @click="showCreateColumn = true" 
                  class="text-xs text-art-accent hover:text-white transition-colors"
                >
                  + 新建专栏
                </button>
              </div>
              <CustomSelect
                  v-model="form.columnId"
                  :options="columns"
                  placeholder="选择专栏（可选）"
              />
              
              <!-- Quick Create Column -->
              <div v-if="showCreateColumn" class="admin-card p-3 space-y-2 mt-2">
                <input
                  v-model="newColumn.name"
                  placeholder="专栏名称"
                  class="admin-input text-sm"
                />
                <div>
                  <label class="block text-xs text-art-muted mb-2">封面图片</label>
                  <ImageUpload
                    v-model="newColumn.cover"
                    :categoryId="1"
                  />
                </div>
                <textarea
                  v-model="newColumn.description"
                  placeholder="描述"
                  rows="2"
                  class="admin-input text-sm"
                />
                <div class="flex gap-2">
                  <button type="button" @click="createColumn" class="admin-btn-primary text-xs px-3 py-1">创建</button>
                  <button type="button" @click="showCreateColumn = false" class="admin-btn-secondary text-xs px-3 py-1">取消</button>
                </div>
              </div>
            </div>
            
            <!-- Tags Field -->
            <div class="space-y-2">
              <div class="flex items-center justify-between">
                <label class="block text-xs font-medium text-art-muted uppercase tracking-wider">标签</label>
                <button 
                  type="button"
                  @click="showCreateTag = true" 
                  class="text-xs text-art-accent hover:text-white transition-colors"
                >
                  + 新建标签
                </button>
              </div>
              <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>
              
              <!-- Quick Create Tag -->
              <div v-if="showCreateTag" class="admin-card p-3 space-y-2 mt-2">
                <input
                  v-model="newTag.name"
                  placeholder="标签名称"
                  class="admin-input text-sm"
                  @keyup.enter="createTag"
                />
                <div class="flex gap-2">
                  <button type="button" @click="createTag" class="admin-btn-primary text-xs px-3 py-1">创建</button>
                  <button type="button" @click="showCreateTag = false" class="admin-btn-secondary text-xs px-3 py-1">取消</button>
                </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>

    <!-- Access Log Modal -->
    <PostHistoryModal
      v-if="isEditing"
      :is-open="isHistoryModalOpen"
      :post-id="route.params.id as string"
      @close="isHistoryModalOpen = false"
      @restored="loadData"
    />
    <AccessLogModal
      v-if="isEditing"
      v-model:isOpen="isAccessLogModalOpen"
      :postId="route.params.id ? parseInt(route.params.id as string) : null"
      :postTitle="form.title || '文章'"
    />
  </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 type { ExposeParam, UploadImgCallBack } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'

import { useToast } from '../../composables/useToast'
import { 
  createPost, 
  updatePost, 
  fetchPost, 
  fetchCategories, 
  fetchColumns, 
  fetchTags, 
  createCategory as createCategoryApi,
  createColumn as createColumnApi,
  createTag as createTagApi,
  Tag 
} from '../../services/api'
import { authFetch, parseApiResponse } from '../../services/api'
import CustomSelect from '../../components/CustomSelect.vue'
import AccessLogModal from '../../components/admin/AccessLogModal.vue'
import PostHistoryModal from '../../components/admin/PostHistoryModal.vue'
import ImageUpload from '../../components/admin/ImageUpload.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>>({})

// Access log modal state
const isAccessLogModalOpen = ref(false)
const isHistoryModalOpen = ref(false)
const openAccessLogModal = () => {
  isAccessLogModalOpen.value = true
}
const openHistoryModal = () => {
  isHistoryModalOpen.value = true
}

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

// Create form states
const showCreateCategory = ref(false)
const showCreateColumn = ref(false)
const showCreateTag = ref(false)

const newCategory = ref({ name: '', slug: '', description: '' })
const newColumn = ref({ name: '', cover: '', description: '', isActive: 1, sortOrder: 0 })
const newTag = ref({ name: '', slug: '' })

// Form data
const form = reactive({
  title: '',
  categoryId: 0,
  columnId: 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)
  }
}

// Create category
const createCategory = async () => {
  if (!newCategory.value.name) {
    toast.showToast('请输入分类名称', 'error')
    return
  }

  try {
    await createCategoryApi({
      name: newCategory.value.name,
      slug: newCategory.value.slug || newCategory.value.name,
      description: newCategory.value.description || '',
      sortOrder: 0
    })
    toast.showToast('分类创建成功', 'success')
    const createdName = newCategory.value.name
    newCategory.value = { name: '', slug: '', description: '' }
    showCreateCategory.value = false
    await loadData()
    // 自动选择新创建的分类
    const newCat = categories.value.find(c => c.label === createdName)
    if (newCat) {
      form.categoryId = newCat.value
    }
  } catch (err: any) {
    toast.showToast(err.message || '创建失败', 'error')
  }
}

// Create column
const createColumn = async () => {
  if (!newColumn.value.name) {
    toast.showToast('请输入专栏名称', 'error')
    return
  }

  try {
    await createColumnApi(newColumn.value)
    toast.showToast('专栏创建成功', 'success')
    const createdName = newColumn.value.name
    newColumn.value = { name: '', cover: '', description: '', isActive: 1, sortOrder: 0 }
    showCreateColumn.value = false
    await loadData()
    // 自动选择新创建的专栏
    const newCol = columns.value.find(c => c.label === createdName)
    if (newCol) {
      form.columnId = newCol.value
    }
  } catch (err: any) {
    toast.showToast(err.message || '创建失败', 'error')
  }
}

// Create tag
const createTag = async () => {
  if (!newTag.value.name) {
    toast.showToast('请输入标签名称', 'error')
    return
  }

  try {
    await createTagApi({
      name: newTag.value.name,
      slug: newTag.value.slug || newTag.value.name
    })
    toast.showToast('标签创建成功', 'success')
    const createdName = newTag.value.name
    newTag.value = { name: '', slug: '' }
    showCreateTag.value = false
    await loadData()
    // 自动选择新创建的标签
    const newTagItem = availableTags.value.find(t => t.name === createdName)
    if (newTagItem && !form.tagIds.includes(newTagItem.id)) {
      form.tagIds.push(newTagItem.id)
    }
  } catch (err: any) {
    toast.showToast(err.message || '创建失败', 'error')
  }
}

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

  isSubmitting.value = true

  try {
    // Construct payload
    const payload: any = {
      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
    }

    // Add columnId if selected
    if (form.columnId > 0) {
      payload.columnId = form.columnId
    } else {
      payload.columnId = null
    }

    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')
}

const editorRef = ref<ExposeParam>()

const uploadMediaFile = async (file: File): Promise<string | null> => {
  const formData = new FormData()
  formData.append('file', file)
  formData.append('categoryId', '1')
  formData.append('storageType', 'local')

  const response = await authFetch('/api/admin/attachments/upload', {
    method: 'POST',
    headers: {},
    body: formData
  })

  const result = await parseApiResponse<{ fileUrl: string }>(response)
  return result?.fileUrl ?? null
}

const insertAtCursor = (text: string) => {
  editorRef.value?.insert?.(() => ({ targetValue: text }))
}

const uploadAndInsertVideo = async (file: File) => {
  try {
    const url = await uploadMediaFile(file)
    if (!url) return
    insertAtCursor(`\n<video controls src="${url}" style="max-width:100%"></video>\n`)
    toast.showToast('视频上传成功', 'success')
  } catch (error: any) {
    console.error('上传视频失败:', error)
    toast.showToast(error.message || '上传视频失败', 'error')
  }
}

const handleUploadImg = async (files: File[], callback: UploadImgCallBack) => {
  try {
    const uploadResults = await Promise.all(
      files.map(async (file) => {
        const url = await uploadMediaFile(file)
        return url ? { url, alt: file.name, title: file.name } : null
      })
    )
    const urls = uploadResults.filter((item): item is { url: string; alt: string; title: string } => item !== null)
    if (urls.length > 0) {
      callback(urls)
      toast.showToast('图片上传成功', 'success')
    }
  } catch (error: any) {
    console.error('上传图片失败:', error)
    toast.showToast(error.message || '上传图片失败', 'error')
  }
}

const handleEditorDrop = async (e: DragEvent) => {
  const files = Array.from(e.dataTransfer?.files || [])
  const imageFiles = files.filter((f) => f.type.startsWith('image/'))
  const videoFiles = files.filter((f) => f.type.startsWith('video/'))
  if (imageFiles.length === 0 && videoFiles.length === 0) return

  e.preventDefault()

  if (imageFiles.length > 0) {
    await handleUploadImg(imageFiles, (urls) => {
      if (!Array.isArray(urls) || urls.length === 0) return
      urls.forEach((item) => {
        if (typeof item === 'string') {
          insertAtCursor(`![image](${item})`)
        } else {
          insertAtCursor(`![${item.alt || 'image'}](${item.url})`)
        }
      })
    })
  }

  for (const file of videoFiles) {
    await uploadAndInsertVideo(file)
  }
}

const handleVideoPaste = async (e: ClipboardEvent) => {
  const items = e.clipboardData?.items
  if (!items) return

  for (let i = 0; i < items.length; i++) {
    const item = items[i]
    if (item.type.startsWith('video/')) {
      e.preventDefault()
      const file = item.getAsFile()
      if (file) await uploadAndInsertVideo(file)
      break
    }
  }
}

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

    // 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.columnId = post.columnId || 0
      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>
