<template>
  <aside class="docs-panel">
    <!-- 头部 -->
    <header class="docs-header">
      <h1 class="docs-header-title">
        <IconLibrary name="folder" :size="20" />
        <span>素材库</span>
      </h1>
      <span class="badge badge-primary">Pro版</span>
    </header>

    <!-- 工具栏 -->
    <div class="docs-toolbar">
      <div class="flex gap-1 flex-wrap">
        <button
          v-for="filter in typeFilters"
          :key="filter.value"
          @click="currentFilter = filter.value"
          :class="['filter-btn', { 'active': currentFilter === filter.value }]"
        >
          <IconLibrary :name="filter.icon" :size="14" class="mr-1" />
          <span>{{ filter.label }}</span>
        </button>
      </div>
      <button
        @click="openAddModal"
        class="create-btn"
      >
        + 新增
      </button>
    </div>

    <!-- 素材列表 -->
    <div class="docs-list">
      <div v-if="filteredMaterials.length === 0" class="text-center text-muted py-8">
        <div class="w-16 h-16 flex items-center justify-center rounded-xl bg-slate-800/50 border border-slate-700 mx-auto mb-3 opacity-40">
          <IconLibrary name="document" :size="32" />
        </div>
        <p class="text-sm">暂无素材</p>
      </div>

      <div
        v-for="material in filteredMaterials"
        :key="material.id"
        @click="selectMaterial(material)"
        :class="['doc-card', { 'selected': selectedId === material.id }]"
      >
        <div class="flex items-start justify-between mb-2">
          <h3 class="font-medium text-primary text-sm truncate flex-1 flex items-center gap-1.5">
            <IconLibrary :name="getTypeIcon(material.type)" :size="14" />
            <span>{{ material.title }}</span>
          </h3>
          <span v-if="material.is_default" class="status-badge archived">
            预置
          </span>
        </div>
        <p class="text-xs text-muted mb-2">{{ material.source || '无来源' }}</p>
        <div class="flex items-center justify-between text-xs text-muted">
          <span>{{ material.excerpts?.length || 0 }} 条摘录</span>
          <div class="flex gap-1">
            <span
              v-for="tag in (material.tags || []).slice(0, 2)"
              :key="tag"
              class="px-1.5 py-0.5 rounded bg-elevated text-muted"
            >
              {{ tag }}
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作区 -->
    <div v-if="selectedId" class="docs-footer">
      <div class="flex gap-2">
        <button
          @click="openEditModal"
          class="action-btn primary flex items-center justify-center gap-1.5"
        >
          <IconLibrary name="edit" :size="14" />
          <span>编辑</span>
        </button>
        <button
          @click="viewExcerpts"
          class="action-btn secondary flex items-center justify-center gap-1.5"
        >
          <IconLibrary name="clipboard" :size="14" />
          <span>查看摘录</span>
        </button>
        <button
          v-if="!selectedMaterial?.is_default"
          @click="confirmDelete"
          class="action-btn danger flex items-center justify-center"
          aria-label="删除素材"
        >
          <IconLibrary name="trash" :size="16" />
        </button>
      </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <div v-if="showEditModal" class="paradigm-modal-backdrop">
      <div class="paradigm-modal flex flex-col" style="max-height: 80vh">
        <div class="p-4 border-b border-default flex items-center justify-between">
          <h3 class="text-lg font-semibold text-primary">{{ isAddMode ? '新增素材' : '编辑素材' }}</h3>
          <button @click="closeEditModal" class="text-muted hover:text-primary">
            <IconLibrary name="close" :size="16" />
          </button>
        </div>

        <div class="flex-1 overflow-y-auto p-4 space-y-4">
          <!-- 素材类型 -->
          <div>
            <label class="block text-xs text-secondary mb-2">素材类型</label>
            <div class="flex flex-wrap gap-2">
              <button
                v-for="type in materialTypes"
                :key="type.value"
                @click="editForm.type = type.value"
                :class="['filter-btn', { 'active': editForm.type === type.value }]"
              >
                <IconLibrary :name="type.icon" :size="14" class="mr-1" />
                <span>{{ type.label }}</span>
              </button>
            </div>
          </div>

          <!-- 标题 -->
          <div>
            <label class="block text-xs text-secondary mb-2">素材标题</label>
            <input
              v-model="editForm.title"
              class="analysis-input"
              placeholder="如：二十届四中全会精神要点"
            >
          </div>

          <!-- 来源 -->
          <div>
            <label class="block text-xs text-secondary mb-2">来源</label>
            <input
              v-model="editForm.source"
              class="analysis-input"
              placeholder="如：人民日报 2024-10-15"
            >
          </div>

          <!-- 标签 -->
          <div>
            <label class="block text-xs text-secondary mb-2">标签（逗号分隔）</label>
            <input
              v-model="editForm.tagsInput"
              class="analysis-input"
              placeholder="如：全面深化改革, 制度建设"
            >
          </div>

          <!-- 关联维度集 -->
          <div>
            <label class="block text-xs text-secondary mb-2">关联维度集</label>
            <select
              v-model="editForm.dimensionSetId"
              class="analysis-input"
            >
              <option value="">不关联</option>
              <option v-for="ds in dimensionSets" :key="ds.id" :value="ds.id">
                {{ ds.name }}
              </option>
            </select>
          </div>

          <!-- 摘录管理 -->
          <div class="border-t border-default pt-4">
            <div class="flex items-center justify-between mb-3">
              <label class="text-xs text-secondary">可引用摘录</label>
              <button
                @click="addExcerpt"
                class="text-xs text-accent hover:opacity-80"
              >
                + 添加摘录
              </button>
            </div>

            <div class="space-y-3" style="max-height: 240px; overflow-y: auto">
              <div
                v-for="(excerpt, index) in editForm.excerpts"
                :key="index"
                class="bg-primary rounded p-3 border border-default"
              >
                <div class="flex items-center justify-between mb-2">
                  <input
                    v-model="excerpt.topic"
                    class="flex-1 bg-transparent border-b border-default text-sm text-primary outline-none focus:border-accent pb-1"
                    placeholder="摘录主题"
                  >
                  <button
                    @click="removeExcerpt(index)"
                    class="text-danger hover:opacity-80 ml-2"
                    aria-label="删除摘录"
                  >
                    <IconLibrary name="close" :size="14" />
                  </button>
                </div>
                <textarea
                  v-model="excerpt.content"
                  class="w-full bg-elevated border border-default rounded px-2 py-1.5 text-xs text-secondary outline-none focus:border-accent resize-none"
                  rows="2"
                  placeholder="摘录内容..."
                ></textarea>
                <div class="flex items-center gap-2 mt-2">
                  <select
                    v-model="excerpt.useFor"
                    class="text-xs bg-elevated border border-default rounded px-2 py-1 text-secondary outline-none"
                  >
                    <option value="">通用</option>
                    <option value="positive">正面案例</option>
                    <option value="negative">反面案例</option>
                  </select>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="p-4 border-t border-default flex gap-3">
          <button
            @click="closeEditModal"
            class="flex-1 action-btn secondary"
          >
            取消
          </button>
          <button
            @click="saveMaterial"
            class="flex-1 action-btn primary"
          >
            {{ isAddMode ? '添加' : '保存' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 摘录查看弹窗 -->
    <div v-if="showExcerptsModal" class="paradigm-modal-backdrop">
      <div class="paradigm-modal flex flex-col" style="max-height: 70vh">
        <div class="p-4 border-b border-default flex items-center justify-between">
          <h3 class="text-lg font-semibold text-primary">{{ selectedMaterial?.title }} - 摘录</h3>
          <button @click="showExcerptsModal = false" class="text-muted hover:text-primary">
            <IconLibrary name="close" :size="16" />
          </button>
        </div>

        <div class="flex-1 overflow-y-auto p-4 space-y-3">
          <div
            v-for="(excerpt, index) in selectedMaterial?.excerpts || []"
            :key="index"
            class="bg-primary rounded p-3 border border-default"
          >
            <div class="flex items-center justify-between mb-2">
              <span class="font-medium text-primary text-sm">{{ excerpt.topic }}</span>
              <span
                v-if="excerpt.useFor"
                :class="['text-xs px-1.5 py-0.5 rounded',
                  excerpt.useFor === 'positive' ? 'bg-success-bg text-success' : 'bg-danger-bg text-danger']"
              >
                {{ excerpt.useFor === 'positive' ? '正面' : '反面' }}
              </span>
            </div>
            <p class="text-xs text-secondary leading-relaxed">{{ excerpt.content }}</p>
          </div>

          <div v-if="!selectedMaterial?.excerpts?.length" class="text-center text-muted py-4">
            暂无摘录
          </div>
        </div>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div v-if="showDeleteConfirm" class="confirm-modal-backdrop">
      <div class="confirm-modal">
        <h3 class="confirm-modal-title">确认删除</h3>
        <p class="confirm-modal-text">确定要删除这条素材吗？此操作不可恢复。</p>
        <div class="confirm-modal-actions">
          <button
            @click="showDeleteConfirm = false"
            class="flex-1 action-btn secondary"
          >
            取消
          </button>
          <button
            @click="deleteMaterial"
            class="flex-1 action-btn danger"
          >
            删除
          </button>
        </div>
      </div>
    </div>
  </aside>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useAppStore } from '../stores/app'
import { REFERENCE_TYPES } from '../config/references.js'
import { getDimensionSetList } from '../config/dimensionSets.js'
import IconLibrary from './icons/IconLibrary.vue'

const appStore = useAppStore()

// 状态
const selectedId = ref(null)
const currentFilter = ref('all')
const showEditModal = ref(false)
const showExcerptsModal = ref(false)
const showDeleteConfirm = ref(false)
const isAddMode = ref(false)

// 素材数据
const materials = ref([])

// 维度集列表
const dimensionSets = getDimensionSetList()

// 素材类型选项
const materialTypes = [
  { value: REFERENCE_TYPES.POLICY, label: '政策文件', icon: 'document' },
  { value: REFERENCE_TYPES.SPEECH, label: '领导讲话', icon: 'microphone' },
  { value: REFERENCE_TYPES.CASE, label: '典型案例', icon: 'bookmark' },
  { value: REFERENCE_TYPES.QUOTE, label: '金句警句', icon: 'sparkles' },
  { value: REFERENCE_TYPES.REGULATION, label: '党规党纪', icon: 'book' }
]

// 类型筛选选项
const typeFilters = [
  { value: 'all', label: '全部', icon: 'folder' },
  ...materialTypes
]

// 编辑表单
const editForm = reactive({
  id: null,
  type: REFERENCE_TYPES.POLICY,
  title: '',
  source: '',
  tagsInput: '',
  dimensionSetId: '',
  excerpts: []
})

// 获取选中的素材
const selectedMaterial = computed(() => {
  return materials.value.find(m => m.id === selectedId.value)
})

// 筛选后的素材
const filteredMaterials = computed(() => {
  if (currentFilter.value === 'all') {
    return materials.value
  }
  return materials.value.filter(m => m.type === currentFilter.value)
})

// 获取类型图标
const getTypeIcon = (type) => {
  const found = materialTypes.find(t => t.value === type)
  return found?.icon || 'document'
}

// 加载素材列表
const loadMaterials = async () => {
  try {
    const { getAllReferences } = await import('../db/index.js')
    materials.value = getAllReferences()
  } catch (error) {
    console.error('加载素材失败:', error)
  }
}

// 选择素材
const selectMaterial = (material) => {
  selectedId.value = selectedId.value === material.id ? null : material.id
}

// 打开新增弹窗
const openAddModal = () => {
  isAddMode.value = true
  editForm.id = null
  editForm.type = REFERENCE_TYPES.POLICY
  editForm.title = ''
  editForm.source = ''
  editForm.tagsInput = ''
  editForm.dimensionSetId = ''
  editForm.excerpts = []
  showEditModal.value = true
}

// 打开编辑弹窗
const openEditModal = () => {
  if (!selectedMaterial.value) return
  
  isAddMode.value = false
  const m = selectedMaterial.value
  editForm.id = m.id
  editForm.type = m.type
  editForm.title = m.title
  editForm.source = m.source || ''
  editForm.tagsInput = (m.tags || []).join(', ')
  editForm.dimensionSetId = m.relatedDimensionSets?.[0] || ''
  editForm.excerpts = (m.excerpts || []).map(e => ({
    topic: e.topic,
    content: e.content,
    useFor: e.useFor || ''
  }))
  showEditModal.value = true
}

// 关闭编辑弹窗
const closeEditModal = () => {
  showEditModal.value = false
}

// 添加摘录
const addExcerpt = () => {
  editForm.excerpts.push({
    topic: '',
    content: '',
    useFor: ''
  })
}

// 删除摘录
const removeExcerpt = (index) => {
  editForm.excerpts.splice(index, 1)
}

// 保存素材
const saveMaterial = async () => {
  if (!editForm.title.trim()) {
    alert('请输入素材标题')
    return
  }
  
  try {
    const { addReference, updateReference } = await import('../db/index.js')
    
    const materialData = {
      type: editForm.type,
      title: editForm.title.trim(),
      source: editForm.source.trim(),
      tags: editForm.tagsInput.split(',').map(t => t.trim()).filter(Boolean),
      relatedDimensionSets: editForm.dimensionSetId ? [editForm.dimensionSetId] : [],
      excerpts: editForm.excerpts.filter(e => e.topic && e.content)
    }
    
    if (isAddMode.value) {
      addReference(materialData)
    } else {
      updateReference(editForm.id, materialData)
    }
    
    await loadMaterials()
    closeEditModal()
  } catch (error) {
    console.error('保存素材失败:', error)
  }
}

// 查看摘录
const viewExcerpts = () => {
  if (!selectedMaterial.value) return
  showExcerptsModal.value = true
}

// 确认删除
const confirmDelete = () => {
  if (!selectedId.value) return
  showDeleteConfirm.value = true
}

// 删除素材
const deleteMaterial = async () => {
  if (!selectedId.value) return
  
  try {
    const { deleteReference } = await import('../db/index.js')
    deleteReference(selectedId.value)
    selectedId.value = null
    showDeleteConfirm.value = false
    await loadMaterials()
  } catch (error) {
    console.error('删除素材失败:', error)
  }
}

// 切换页面
const switchPage = (page) => {
  appStore.setCurrentPage(page)
}

onMounted(() => {
  loadMaterials()
})
</script>

<style scoped>
/* ========== 使用设计令牌系统 ========== */

/* 侧边栏容器 */
.docs-panel {
  width: 400px;
  height: 100vh;
  display: flex;
  flex-direction: column;
  border-right: 1px solid var(--border-default);
  background: var(--bg-secondary);
  flex-shrink: 0;
}

/* 头部 */
.docs-header {
  padding: var(--space-4);
  border-bottom: 1px solid var(--border-default);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.docs-header-title {
  font-weight: var(--font-semibold);
  font-size: var(--text-lg);
  color: var(--text-primary);
  display: flex;
  align-items: center;
  gap: var(--space-2);
}

/* 工具栏 */
.docs-toolbar {
  padding: var(--space-4);
  border-bottom: 1px solid var(--border-default);
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: var(--space-2);
}

/* 筛选按钮 */
.filter-btn {
  font-size: var(--text-xs);
  padding: var(--space-2) var(--space-3);
  border-radius: var(--radius-md);
  transition: all var(--transition-fast);
}

.filter-btn.active {
  background: var(--accent-primary);
  color: var(--text-inverse);
}

.filter-btn:not(.active) {
  background: var(--bg-elevated);
  color: var(--text-secondary);
}

.filter-btn:not(.active):hover {
  background: var(--bg-sunken);
  color: var(--text-primary);
}

/* 素材列表 */
.docs-list {
  flex: 1;
  overflow-y: auto;
  padding: var(--space-4);
}

/* 素材卡片 */
.doc-card {
  padding: var(--space-3);
  border-radius: var(--radius-lg);
  border: 1px solid var(--border-default);
  cursor: pointer;
  transition: all var(--transition-fast);
  margin-bottom: var(--space-3);
}

.doc-card.selected {
  background: var(--info-bg);
  border-color: var(--accent-primary);
}

.doc-card:not(.selected) {
  background: var(--bg-primary);
}

.doc-card:not(.selected):hover {
  border-color: var(--border-strong);
}

/* 状态徽章 */
.status-badge {
  font-size: var(--text-xs);
  padding: 2px 6px;
  border-radius: var(--radius-sm);
}

.status-badge.archived {
  background: var(--bg-elevated);
  color: var(--text-secondary);
}

/* 底部操作区 */
.docs-footer {
  padding: var(--space-4);
  border-top: 1px solid var(--border-default);
}

/* 操作按钮 */
.action-btn {
  flex: 1;
  font-size: var(--text-xs);
  padding: var(--space-2);
  border-radius: var(--radius-md);
  transition: all var(--transition-fast);
}

.action-btn.primary {
  background: var(--accent-primary);
  color: var(--text-inverse);
}

.action-btn.primary:hover {
  background: var(--accent-primary-hover);
}

.action-btn.secondary {
  background: var(--bg-elevated);
  color: var(--text-primary);
}

.action-btn.secondary:hover {
  background: var(--bg-sunken);
}

.action-btn.danger {
  background: var(--danger-bg);
  color: var(--accent-danger);
}

.action-btn.danger:hover {
  background: rgba(248, 113, 113, 0.2);
}

/* 新建按钮 */
.create-btn {
  font-size: var(--text-xs);
  padding: var(--space-2) var(--space-3);
  border-radius: var(--radius-md);
  background: var(--accent-success);
  color: var(--text-inverse);
  transition: all var(--transition-fast);
}

.create-btn:hover {
  background: #22c55e;
}

/* 确认弹窗 */
.confirm-modal-backdrop {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: var(--z-modal-backdrop);
}

.confirm-modal {
  background: var(--bg-secondary);
  border-radius: var(--radius-lg);
  padding: var(--space-6);
  width: 320px;
  border: 1px solid var(--border-default);
}

.confirm-modal-title {
  font-size: var(--text-lg);
  font-weight: var(--font-semibold);
  color: var(--text-primary);
  margin-bottom: var(--space-4);
}

.confirm-modal-text {
  font-size: var(--text-sm);
  color: var(--text-secondary);
  margin-bottom: var(--space-6);
}

.confirm-modal-actions {
  display: flex;
  gap: var(--space-3);
}

/* 范式模态框 */
.paradigm-modal-backdrop {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: var(--z-modal-backdrop);
}

.paradigm-modal {
  background: var(--bg-secondary);
  border-radius: var(--radius-lg);
  width: 500px;
  max-height: 80vh;
  overflow: hidden;
  border: 1px solid var(--border-default);
  display: flex;
  flex-direction: column;
}

/* 输入框 */
.analysis-input {
  width: 100%;
  background: var(--bg-primary);
  border: 1px solid var(--border-default);
  border-radius: var(--radius-md);
  padding: var(--space-2) var(--space-3);
  font-size: var(--text-sm);
  color: var(--text-primary);
  outline: none;
  transition: border-color var(--transition-fast);
}

.analysis-input:focus {
  border-color: var(--accent-primary);
}

/* 徽章 */
.badge {
  font-size: var(--text-xs);
  padding: 2px 6px;
  border-radius: var(--radius-sm);
}

.badge-primary {
  background: var(--accent-primary);
  color: var(--text-inverse);
}
</style>
