<template>
  <aside class="docs-panel">
    <!-- 头部 -->
    <header class="docs-header">
      <h1 class="docs-header-title">
        <IconLibrary name="settings" :size="20" />
        <span>设置中心</span>
      </h1>
      <span class="badge badge-primary">Pro版</span>
    </header>

    <!-- 设置内容 -->
    <div class="flex-1 overflow-y-auto p-4 space-y-6 min-h-0">

      <!-- AI 模型设置 -->
      <section class="settings-section">
        <h3 class="settings-section-title">
          <IconLibrary name="cpu" :size="16" />
          <span>AI 模型设置</span>
        </h3>
        <div class="space-y-3">
          <div>
            <label class="settings-label">模型服务商</label>
            <select
              v-model="selectedProviderId"
              class="settings-select"
            >
              <option 
                v-for="provider in availableProviders" 
                :key="provider.id" 
                :value="provider.id"
              >
                {{ provider.name }} - {{ provider.description }}
              </option>
            </select>
          </div>
          
          <!-- 当前配置状态 -->
          <div class="provider-status">
            <div class="status-row">
              <span class="status-label">API 端点</span>
              <span class="status-value truncate">{{ currentProvider?.apiUrl || '未配置' }}</span>
            </div>
            <div class="status-row">
              <span class="status-label">API Key</span>
              <span :class="['status-value flex items-center gap-1', currentProvider?.apiKey ? 'configured' : 'not-configured']">
                <IconLibrary v-if="currentProvider?.apiKey" name="check" :size="12" />
                <IconLibrary v-else name="close" :size="12" />
                {{ currentProvider?.apiKey ? '已配置' : '未配置' }}
              </span>
            </div>
            <div class="status-row" v-if="currentProvider?.model">
              <span class="status-label">默认模型</span>
              <span class="status-value">{{ currentProvider.model }}</span>
            </div>
          </div>
          
          <p class="text-xs text-muted flex items-center gap-1.5">
            <IconLibrary name="info" :size="14" />
            <span>模型配置通过 <code>.env</code> 文件设置，详见项目文档</span>
          </p>
        </div>
      </section>

      <!-- 数据统计 -->
      <section class="settings-section">
        <h3 class="settings-section-title">
          <IconLibrary name="chart" :size="16" />
          <span>数据统计</span>
        </h3>
        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-value blue">{{ stats.documents }}</div>
            <div class="stat-label">文稿数量</div>
          </div>
          <div class="stat-card">
            <div class="stat-value green">{{ stats.materials }}</div>
            <div class="stat-label">素材数量</div>
          </div>
          <div class="stat-card">
            <div class="stat-value purple">{{ stats.paradigms }}</div>
            <div class="stat-label">范式数量</div>
          </div>
          <div class="stat-card">
            <div class="stat-value amber">{{ formatSize(stats.dbSize) }}</div>
            <div class="stat-label">数据库大小</div>
          </div>
        </div>
      </section>

      <!-- 素材库管理 -->
      <section class="settings-section">
        <h3 class="settings-section-title">
          <IconLibrary name="folder" :size="16" />
          <span>素材库管理</span>
        </h3>
        <div class="space-y-3">
          <button
            @click="openMaterialsEditor"
            class="settings-btn secondary"
          >
            <span>管理素材库</span>
            <span class="text-muted">{{ stats.materials }} 条</span>
          </button>
          <button
            @click="importMaterials"
            class="settings-btn secondary flex items-center gap-2"
          >
            <IconLibrary name="download" :size="14" />
            <span>导入素材 (JSON)</span>
          </button>
        </div>
      </section>

      <!-- 数据备份 -->
      <section class="settings-section">
        <h3 class="settings-section-title">
          <IconLibrary name="save" :size="16" />
          <span>数据备份与恢复</span>
        </h3>
        <div class="space-y-3">
          <button
            @click="exportData"
            class="settings-btn primary flex items-center justify-center gap-2"
          >
            <IconLibrary name="upload" :size="14" />
            <span>导出所有数据 (JSON)</span>
          </button>
          <button
            @click="triggerImport"
            class="settings-btn secondary flex items-center justify-center gap-2"
          >
            <IconLibrary name="download" :size="14" />
            <span>导入数据</span>
          </button>
          <input
            ref="importInput"
            type="file"
            accept=".json"
            class="hidden"
            @change="handleImport"
          >
        </div>
      </section>

      <!-- 危险操作 -->
      <section class="settings-section danger-section">
        <h3 class="settings-section-title">
          <IconLibrary name="warning" :size="16" />
          <span>危险操作</span>
        </h3>
        <div class="space-y-3">
          <button
            @click="confirmClearDocuments"
            class="settings-btn danger-btn"
          >
            清空所有文稿
          </button>
          <button
            @click="confirmResetDatabase"
            class="settings-btn danger-btn"
          >
            重置数据库（恢复默认）
          </button>
        </div>
      </section>

      <!-- 关于 -->
      <section class="settings-section">
        <h3 class="settings-section-title">
          <IconLibrary name="info" :size="16" />
          <span>关于</span>
        </h3>
        <div class="text-xs text-muted space-y-1">
          <p>AI 写作工坊 v1.0.0</p>
          <p>数据存储：浏览器 IndexedDB (SQLite)</p>
          <p>© 2026 AI Writing Workshop</p>
        </div>
      </section>
    </div>

    <!-- 确认弹窗 -->
    <div v-if="showConfirm" class="confirm-modal-backdrop">
      <div class="confirm-modal">
        <h3 class="confirm-modal-title">{{ confirmTitle }}</h3>
        <p class="confirm-modal-text">{{ confirmMessage }}</p>
        <div class="confirm-modal-actions">
          <button
            @click="showConfirm = false"
            class="settings-btn secondary"
          >
            取消
          </button>
          <button
            @click="executeConfirmAction"
            class="settings-btn danger-btn"
          >
            确认
          </button>
        </div>
      </div>
    </div>

    <!-- 成功提示 -->
    <div v-if="showToast" class="toast">
      {{ toastMessage }}
    </div>
  </aside>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { storeToRefs } from 'pinia'
import { useAppStore } from '../stores/app'
import { modelProviders, getConfiguredProviders } from '../utils/config.js'
import IconLibrary from './icons/IconLibrary.vue'

const appStore = useAppStore()
const { selectedProviderId, currentProvider } = storeToRefs(appStore)

// 获取所有可选的服务商（包括已配置和未配置的）
const availableProviders = computed(() => {
  return Object.values(modelProviders)
})

// 状态
const stats = reactive({
  documents: 0,
  materials: 0,
  paradigms: 0,
  dbSize: 0
})

const showConfirm = ref(false)
const confirmTitle = ref('')
const confirmMessage = ref('')
const confirmAction = ref(null)

const showToast = ref(false)
const toastMessage = ref('')

const importInput = ref(null)

// 加载统计数据
const loadStats = async () => {
  try {
    const { getAllDocuments, getAllReferences, getAllParadigms, exportDatabase } = await import('../db/index.js')
    
    stats.documents = getAllDocuments().length
    stats.materials = getAllReferences().length
    stats.paradigms = getAllParadigms().length
    
    const dbData = exportDatabase()
    stats.dbSize = dbData.length
  } catch (error) {
    console.error('加载统计失败:', error)
  }
}

// 格式化大小
const formatSize = (bytes) => {
  if (bytes < 1024) return bytes + ' B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
  return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
}

// 导出数据
const exportData = async () => {
  try {
    const { exportAsJSON } = await import('../db/index.js')
    const data = exportAsJSON()
    
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `ai-writer-backup-${new Date().toISOString().split('T')[0]}.json`
    a.click()
    URL.revokeObjectURL(url)
    
    showToastMessage('数据导出成功')
  } catch (error) {
    console.error('导出失败:', error)
  }
}

// 触发导入
const triggerImport = () => {
  importInput.value?.click()
}

// 处理导入
const handleImport = async (event) => {
  const file = event.target.files?.[0]
  if (!file) return
  
  try {
    const text = await file.text()
    const data = JSON.parse(text)
    
    // TODO: 实现导入逻辑
    console.log('导入数据:', data)
    showToastMessage('数据导入成功')
    await loadStats()
  } catch (error) {
    console.error('导入失败:', error)
  }
}

// 打开素材编辑器
const openMaterialsEditor = () => {
  // TODO: 打开素材管理弹窗
  showToastMessage('素材管理功能开发中...')
}

// 导入素材
const importMaterials = () => {
  // TODO: 导入素材
  showToastMessage('素材导入功能开发中...')
}

// 确认清空文稿
const confirmClearDocuments = () => {
  confirmTitle.value = '清空所有文稿'
  confirmMessage.value = '确定要删除所有文稿吗？此操作不可恢复！'
  confirmAction.value = 'clearDocuments'
  showConfirm.value = true
}

// 确认重置数据库
const confirmResetDatabase = () => {
  confirmTitle.value = '重置数据库'
  confirmMessage.value = '确定要重置数据库吗？所有数据将被删除并恢复默认设置！'
  confirmAction.value = 'resetDatabase'
  showConfirm.value = true
}

// 执行确认操作
const executeConfirmAction = async () => {
  showConfirm.value = false
  
  try {
    if (confirmAction.value === 'clearDocuments') {
      const { query, execute } = await import('../db/index.js')
      execute('DELETE FROM document_versions')
      execute('DELETE FROM documents')
      showToastMessage('文稿已清空')
    } else if (confirmAction.value === 'resetDatabase') {
      const { resetDatabase } = await import('../db/index.js')
      await resetDatabase()
      showToastMessage('数据库已重置')
    }
    
    await loadStats()
  } catch (error) {
    console.error('操作失败:', error)
  }
}

// 显示提示
const showToastMessage = (message) => {
  toastMessage.value = message
  showToast.value = true
  setTimeout(() => {
    showToast.value = false
  }, 2000)
}

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

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

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

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

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

/* 内容区 */
.settings-content {
  flex: 1;
  overflow-y: auto;
  padding: var(--space-4);
}

/* 设置区块 */
.settings-section {
  background: var(--bg-primary);
  border-radius: var(--radius-lg);
  padding: var(--space-4);
  border: 1px solid var(--border-default);
  margin-bottom: var(--space-6);
}

.settings-section:last-child {
  margin-bottom: 0;
}

.settings-section-title {
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  color: var(--text-primary);
  margin-bottom: var(--space-4);
  display: flex;
  align-items: center;
  gap: var(--space-2);
}

/* 统计卡片网格 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: var(--space-3);
}

.stat-card {
  background: var(--bg-elevated);
  border-radius: var(--radius-md);
  padding: var(--space-3);
  text-align: center;
}

.stat-value {
  font-size: var(--text-2xl);
  font-weight: var(--font-semibold);
  font-variant-numeric: tabular-nums;
}

.stat-value.blue { color: var(--accent-primary); }
.stat-value.green { color: var(--accent-success); }
.stat-value.purple { color: #a855f7; }
.stat-value.amber { color: var(--accent-warning); }

.stat-label {
  font-size: var(--text-xs);
  color: var(--text-muted);
}

/* 设置输入框和标签 */
.settings-label {
  display: block;
  font-size: var(--text-xs);
  color: var(--text-muted);
  margin-bottom: var(--space-1);
}

.settings-input {
  width: 100%;
  background: var(--bg-elevated);
  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);
}

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

.settings-input::placeholder {
  color: var(--text-muted);
}

/* 选择框 */
.settings-select {
  width: 100%;
  background: var(--bg-elevated);
  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;
  cursor: pointer;
  transition: border-color var(--transition-fast);
}

.settings-select:focus {
  border-color: var(--accent-primary);
}

.settings-select option {
  background: var(--bg-secondary);
  color: var(--text-primary);
}

/* 服务商状态显示 */
.provider-status {
  background: var(--bg-elevated);
  border-radius: var(--radius-md);
  padding: var(--space-3);
  font-size: var(--text-xs);
}

.status-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--space-1) 0;
}

.status-row:not(:last-child) {
  border-bottom: 1px solid var(--border-default);
}

.status-label {
  color: var(--text-muted);
}

.status-value {
  color: var(--text-secondary);
  max-width: 200px;
}

.status-value.configured {
  color: var(--accent-success);
}

.status-value.not-configured {
  color: var(--accent-danger);
}

.status-value.truncate {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 设置按钮 */
.settings-btn {
  width: 100%;
  text-align: left;
  font-size: var(--text-xs);
  padding: var(--space-3);
  border-radius: var(--radius-md);
  transition: all var(--transition-fast);
  display: flex;
  align-items: center;
  justify-content: space-between;
  border: none;
  cursor: pointer;
}

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

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

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

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

/* 危险操作区块 */
.danger-section {
  background: var(--danger-bg);
  border: 1px solid rgba(248, 113, 113, 0.5);
}

.danger-section .settings-section-title {
  color: var(--accent-danger);
}

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

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

/* 确认弹窗 */
.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-message {
  font-size: var(--text-sm);
  color: var(--text-secondary);
  margin-bottom: var(--space-6);
}

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

/* Toast 提示 */
.toast {
  position: fixed;
  bottom: var(--space-4);
  right: var(--space-4);
  background: var(--accent-success);
  color: var(--text-inverse);
  padding: var(--space-3) var(--space-4);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-lg);
  z-index: var(--z-modal);
}
</style>
