<template>
  <div class="model-settings">
    <!-- 背景效果 -->
    <div class="bg-effects">
      <div class="glow-orb glow-1"></div>
      <div class="glow-orb glow-2"></div>
    </div>

    <!-- 页面头部 -->
    <header class="page-header">
      <div class="header-left">
        <el-button text class="back-btn" @click="goHome">
          <el-icon><ArrowLeft /></el-icon>
          <span>返回</span>
        </el-button>
      </div>
      <div class="header-content">
        <h1 class="page-title">
          <el-icon class="title-icon"><Cpu /></el-icon>
          模型配置
        </h1>
        <p class="page-subtitle">管理您的 AI 模型 API 配置</p>
      </div>
      <div class="header-right">
        <el-button type="primary" class="add-btn" @click="openAddDialog">
          <el-icon><Plus /></el-icon>
          <span>添加模型</span>
        </el-button>
      </div>
    </header>

    <!-- 主内容 -->
    <main class="page-main">
      <!-- 统计卡片 -->
      <section class="stats-grid">
        <div class="stat-card" v-for="stat in stats" :key="stat.label">
          <div class="stat-icon" :class="stat.class">
            {{ stat.icon }}
          </div>
          <div class="stat-info">
            <span class="stat-value">{{ stat.value }}</span>
            <span class="stat-label">{{ stat.label }}</span>
          </div>
        </div>
      </section>

      <!-- 模型列表 -->
      <section class="models-section">
        <div class="section-header">
          <h2 class="section-title">
            <span class="title-line"></span>
            已配置的模型
          </h2>
          <span class="count-badge">{{ models.length }} 个</span>
        </div>

        <!-- 空状态 -->
        <div v-if="models.length === 0 && !loading" class="empty-state">
          <div class="empty-illustration">
            <div class="pulse-ring"></div>
            <el-icon size="48"><Setting /></el-icon>
          </div>
          <h3>暂无模型配置</h3>
          <p>添加您的第一个 AI 模型开始使用</p>
          <el-button type="primary" @click="openAddDialog">添加模型</el-button>
        </div>

        <!-- 模型卡片 -->
        <div v-else class="models-grid">
          <article
            v-for="(model, index) in models"
            :key="model.id"
            class="model-card"
            :class="{ 'is-default': model.is_default === 'true' }"
            :style="{ '--delay': index * 0.08 + 's' }"
          >
            <div class="card-glow"></div>

            <!-- 默认标识 -->
            <div v-if="model.is_default === 'true'" class="default-badge">
              <el-icon><Star /></el-icon>
              默认
            </div>

            <!-- 提供商图标 -->
            <div class="provider-logo" :class="model.provider">
              {{ getProviderAbbr(model.provider) }}
            </div>

            <!-- 模型信息 -->
            <div class="model-info">
              <h3 class="model-name">{{ model.model_name }}</h3>
              <p class="model-endpoint">
                <el-icon><Link /></el-icon>
                {{ model.api_base || '默认端点' }}
              </p>
            </div>

            <!-- 底部操作 -->
            <div class="card-footer">
              <div class="status-badge">
                <span class="status-dot online"></span>
                已配置
              </div>
              <div class="card-actions">
                <el-tooltip content="测试连接" placement="top">
                  <el-button text circle class="action-btn" @click="testConnection(model)">
                    <el-icon><Connection /></el-icon>
                  </el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button text circle class="action-btn delete" @click="confirmDelete(model)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </el-tooltip>
              </div>
            </div>
          </article>
        </div>
      </section>
    </main>

    <!-- 添加模型弹窗 -->
    <el-dialog
      v-model="showAddDialog"
      :show-close="false"
      width="500"
      class="model-dialog"
      :append-to-body="true"
    >
      <template #header>
        <div class="dialog-header">
          <div class="dialog-icon">
            <el-icon size="20"><Plus /></el-icon>
          </div>
          <div class="dialog-title">
            <h3>添加模型</h3>
            <p>配置新的 AI 模型</p>
          </div>
          <button class="dialog-close" @click="showAddDialog = false">
            <el-icon><Close /></el-icon>
          </button>
        </div>
      </template>

      <el-form :model="modelForm" label-position="top" class="model-form">
        <!-- 提供商选择 -->
        <el-form-item label="选择提供商">
          <div class="provider-grid">
            <div
              v-for="provider in providers"
              :key="provider.value"
              class="provider-option"
              :class="{ active: modelForm.provider === provider.value }"
              @click="modelForm.provider = provider.value"
            >
              <span class="provider-abbr">{{ provider.abbr }}</span>
              <span class="provider-name">{{ provider.label }}</span>
            </div>
          </div>
        </el-form-item>

        <!-- 模型名称 -->
        <el-form-item label="模型名称" required>
          <el-input
            v-model="modelForm.model_name"
            placeholder="例如: gpt-4o-mini"
            size="large"
          />
        </el-form-item>

        <!-- API Key -->
        <el-form-item label="API Key" required>
          <el-input
            v-model="modelForm.api_key"
            type="password"
            placeholder="输入 API Key"
            size="large"
            show-password
          />
        </el-form-item>

        <!-- API 地址 -->
        <el-form-item label="API 地址 (可选)">
          <el-input
            v-model="modelForm.api_base"
            placeholder="自定义 API 地址"
            size="large"
          />
        </el-form-item>

        <!-- 默认开关 -->
        <el-form-item>
          <el-checkbox v-model="modelForm.is_default">
            设为默认模型
          </el-checkbox>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showAddDialog = false" size="large">取消</el-button>
          <el-button type="primary" @click="addModel" :loading="submitting" size="large">
            添加模型
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog
      v-model="deleteDialogVisible"
      :show-close="false"
      width="400"
      class="delete-dialog"
      :append-to-body="true"
    >
      <template #header>
        <div class="delete-header">
          <div class="delete-icon">
            <el-icon size="24"><WarningFilled /></el-icon>
          </div>
          <h3>确认删除</h3>
        </div>
      </template>

      <div class="delete-content">
        <p>确定要删除模型 <strong>{{ modelToDelete?.model_name }}</strong> 吗？</p>
        <p class="warning-text">此操作不可恢复</p>
      </div>

      <template #footer>
        <div class="delete-footer">
          <el-button @click="deleteDialogVisible = false" size="large">取消</el-button>
          <el-button type="danger" @click="handleDelete" :loading="deleting" size="large">
            确认删除
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { ModelConfig, ProviderOption, ModelCreate } from '@/types'

const router = useRouter()

// 状态
const loading = ref(false)
const submitting = ref(false)
const deleting = ref(false)
const showAddDialog = ref(false)
const deleteDialogVisible = ref(false)
const modelToDelete = ref<ModelConfig | null>(null)
const models = ref<ModelConfig[]>([])

// 表单
const modelForm = reactive<ModelCreate>({
  provider: 'openai',
  model_name: '',
  api_key: '',
  api_base: '',
  is_default: false
})

// 提供商
const providers: ProviderOption[] = [
  { value: 'openai', label: 'OpenAI', abbr: 'OP' },
  { value: 'anthropic', label: 'Anthropic', abbr: 'AN' },
  { value: 'google', label: 'Google', abbr: 'GO' },
  { value: 'other', label: '其他', abbr: 'OT' }
]

// Mock
const mockModels: ModelConfig[] = [
  { id: '1', provider: 'openai', model_name: 'gpt-4o', api_base: 'https://api.openai.com/v1', is_default: 'true' },
  { id: '2', provider: 'openai', model_name: 'gpt-4o-mini', api_base: 'https://api.openai.com/v1', is_default: 'false' },
  { id: '3', provider: 'anthropic', model_name: 'claude-3-5-sonnet', api_base: 'https://api.anthropic.com', is_default: 'false' }
]

// 统计
const stats = computed(() => [
  { label: 'OpenAI', value: models.value.filter(m => m.provider === 'openai').length, icon: 'OP', class: 'openai' },
  { label: 'Anthropic', value: models.value.filter(m => m.provider === 'anthropic').length, icon: 'AN', class: 'anthropic' },
  { label: 'Google', value: models.value.filter(m => m.provider === 'google').length, icon: 'GO', class: 'google' },
  { label: '默认模型', value: models.value.find(m => m.is_default === 'true')?.model_name || '未设置', icon: '★', class: 'default' }
])

// 方法
const goHome = () => router.push('/')

const getProviderAbbr = (provider: string) => {
  const p = providers.find(p => p.value === provider)
  return p?.abbr || '?'
}

const fetchModels = async () => {
  loading.value = true
  try {
    await new Promise(r => setTimeout(r, 500))
    models.value = mockModels
  } catch {
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

const openAddDialog = () => {
  modelForm.provider = 'openai'
  modelForm.model_name = ''
  modelForm.api_key = ''
  modelForm.api_base = ''
  modelForm.is_default = false
  showAddDialog.value = true
}

const addModel = async () => {
  if (!modelForm.model_name || !modelForm.api_key) {
    ElMessage.warning('请填写模型名称和 API Key')
    return
  }

  submitting.value = true
  try {
    await new Promise(r => setTimeout(r, 500))
    ElMessage.success('添加成功')
    showAddDialog.value = false
    fetchModels()
  } catch {
    ElMessage.error('添加失败')
  } finally {
    submitting.value = false
  }
}

const confirmDelete = (model: ModelConfig) => {
  modelToDelete.value = model
  deleteDialogVisible.value = true
}

const handleDelete = async () => {
  deleting.value = true
  try {
    await new Promise(r => setTimeout(r, 500))
    ElMessage.success('删除成功')
    deleteDialogVisible.value = false
    modelToDelete.value = null
    fetchModels()
  } catch {
    ElMessage.error('删除失败')
  } finally {
    deleting.value = false
  }
}

const testConnection = (model: ModelConfig) => {
  ElMessage.info(`测试 ${model.model_name}...`)
}

onMounted(() => fetchModels())
</script>

<style scoped>
/* 使用全局 CSS 变量 */
.model-settings {
  min-height: 100vh;
  background: var(--bg-primary);
  position: relative;
  overflow: hidden;
}

/* 背景效果 */
.bg-effects {
  position: fixed;
  inset: 0;
  pointer-events: none;
  z-index: 0;
}

.glow-orb {
  position: absolute;
  border-radius: 50%;
  filter: blur(120px);
  opacity: 0.4;
}

.glow-1 {
  width: 500px;
  height: 500px;
  background: var(--accent-primary);
  top: -200px;
  right: -100px;
}

.glow-2 {
  width: 400px;
  height: 400px;
  background: var(--accent-secondary);
  bottom: -100px;
  left: -100px;
}

/* 页面头部 */
.page-header {
  position: relative;
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 32px;
  background: var(--bg-secondary);
  border-bottom: 1px solid var(--border-subtle);
}

.header-content {
  text-align: center;
}

.page-title {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  font-size: 22px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.title-icon {
  color: var(--accent-primary);
}

.page-subtitle {
  font-size: 13px;
  color: var(--text-tertiary);
  margin: 4px 0 0;
}

.header-left, .header-right {
  flex: 1;
}

.header-right {
  display: flex;
  justify-content: flex-end;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  color: var(--text-secondary);
  padding: 8px 16px;
  border-radius: var(--radius-md);
  background: transparent !important;
}

.back-btn:hover {
  background: var(--bg-hover) !important;
  color: var(--text-primary);
}

.add-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  background: var(--accent-primary);
  border: none;
  color: #030407;
  font-weight: 600;
}

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

/* 主内容 */
.page-main {
  position: relative;
  z-index: 1;
  max-width: 1200px;
  margin: 0 auto;
  padding: 32px;
}

/* 统计卡片 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 32px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: var(--bg-secondary);
  border: 1px solid var(--border-subtle);
  border-radius: var(--radius-lg);
  transition: all var(--transition-fast);
}

.stat-card:hover {
  border-color: var(--border-default);
  transform: translateY(-2px);
}

.stat-icon {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: var(--radius-md);
  font-size: 14px;
  font-weight: 700;
  color: white;
}

.stat-icon.openai { background: linear-gradient(135deg, #10a37f, #0d8c6d); }
.stat-icon.anthropic { background: linear-gradient(135deg, #d97757, #c45f3f); }
.stat-icon.google { background: linear-gradient(135deg, #4285f4, #3367d6); }
.stat-icon.default { background: linear-gradient(135deg, var(--accent-primary), var(--accent-secondary)); }

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
}

.stat-label {
  font-size: 12px;
  color: var(--text-tertiary);
}

/* 模型列表 */
.models-section {
  background: var(--bg-secondary);
  border: 1px solid var(--border-subtle);
  border-radius: var(--radius-xl);
  padding: 24px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.title-line {
  width: 4px;
  height: 18px;
  background: linear-gradient(180deg, var(--accent-primary), var(--accent-secondary));
  border-radius: 2px;
}

.count-badge {
  font-size: 12px;
  color: var(--text-tertiary);
  background: var(--bg-hover);
  padding: 6px 14px;
  border-radius: 20px;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 80px 20px;
}

.empty-illustration {
  position: relative;
  width: 100px;
  height: 100px;
  margin: 0 auto 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-muted);
}

.pulse-ring {
  position: absolute;
  inset: 0;
  border: 2px solid var(--border-subtle);
  border-radius: 50%;
  animation: pulse 2s ease-in-out infinite;
}

@keyframes pulse {
  0%, 100% { transform: scale(1); opacity: 1; }
  50% { transform: scale(1.1); opacity: 0.5; }
}

.empty-state h3 {
  font-size: 18px;
  color: var(--text-primary);
  margin: 0 0 8px;
}

.empty-state p {
  color: var(--text-tertiary);
  margin: 0 0 24px;
}

/* 模型网格 */
.models-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.model-card {
  position: relative;
  padding: 24px;
  background: var(--bg-tertiary);
  border: 1px solid var(--border-subtle);
  border-radius: var(--radius-lg);
  transition: all var(--transition-base);
  animation: fadeInUp 0.4s ease backwards;
  animation-delay: var(--delay);
}

@keyframes fadeInUp {
  from { opacity: 0; transform: translateY(16px); }
  to { opacity: 1; transform: translateY(0); }
}

.model-card:hover {
  border-color: var(--accent-primary-muted);
  transform: translateY(-4px);
  box-shadow: var(--glow-primary);
}

.model-card.is-default {
  border-color: rgba(52, 211, 153, 0.3);
}

.card-glow {
  position: absolute;
  inset: 0;
  border-radius: var(--radius-lg);
  background: radial-gradient(circle at top right, var(--accent-primary-muted), transparent 60%);
  opacity: 0;
  transition: opacity var(--transition-base);
}

.model-card:hover .card-glow {
  opacity: 1;
}

.default-badge {
  position: absolute;
  top: 16px;
  right: 16px;
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 11px;
  color: var(--success);
  background: var(--success-muted);
  padding: 4px 10px;
  border-radius: 6px;
}

.provider-logo {
  width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: var(--radius-md);
  font-size: 13px;
  font-weight: 700;
  color: white;
  margin-bottom: 16px;
}

.provider-logo.openai { background: linear-gradient(135deg, #10a37f, #0d8c6d); }
.provider-logo.anthropic { background: linear-gradient(135deg, #d97757, #c45f3f); }
.provider-logo.google { background: linear-gradient(135deg, #4285f4, #3367d6); }
.provider-logo.other { background: linear-gradient(135deg, #6b7280, #4b5563); }

.model-info {
  margin-bottom: 20px;
}

.model-name {
  font-size: 17px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 8px;
}

.model-endpoint {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: var(--text-muted);
  margin: 0;
}

.card-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 16px;
  border-top: 1px solid var(--border-subtle);
}

.status-badge {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: var(--text-secondary);
}

.status-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: var(--text-muted);
}

.status-dot.online {
  background: var(--success);
  box-shadow: 0 0 8px var(--success);
}

.card-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  width: 32px;
  height: 32px;
  color: var(--text-tertiary);
  background: var(--bg-hover);
  border-radius: var(--radius-sm);
}

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

.action-btn.delete:hover {
  color: var(--danger);
  background: var(--danger-muted);
}

/* 弹窗样式 */
:deep(.model-dialog .el-dialog) {
  background: var(--bg-elevated);
  border: 1px solid var(--border-subtle);
  border-radius: var(--radius-xl);
}

.dialog-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px 24px;
  position: relative;
}

.dialog-icon {
  width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--accent-primary);
  border-radius: var(--radius-md);
  color: #030407;
}

.dialog-title h3 {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.dialog-title p {
  font-size: 13px;
  color: var(--text-tertiary);
  margin: 4px 0 0;
}

.dialog-close {
  position: absolute;
  right: 16px;
  top: 50%;
  transform: translateY(-50%);
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: transparent;
  border: none;
  border-radius: var(--radius-sm);
  color: var(--text-tertiary);
  cursor: pointer;
}

.dialog-close:hover {
  background: var(--bg-hover);
  color: var(--text-primary);
}

.provider-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
}

.provider-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 16px 8px;
  background: var(--bg-tertiary);
  border: 1px solid var(--border-subtle);
  border-radius: var(--radius-md);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.provider-option:hover {
  border-color: var(--border-default);
}

.provider-option.active {
  border-color: var(--accent-primary);
  background: var(--accent-primary-muted);
}

.provider-option .provider-abbr {
  font-size: 14px;
  font-weight: 700;
  color: var(--text-primary);
}

.provider-option .provider-name {
  font-size: 11px;
  color: var(--text-tertiary);
}

.provider-option.active .provider-name {
  color: var(--accent-primary);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px;
  background: var(--bg-tertiary);
  border-top: 1px solid var(--border-subtle);
}

/* 删除弹窗 */
:deep(.delete-dialog .el-dialog) {
  background: var(--bg-elevated);
  border: 1px solid var(--danger-muted);
  border-radius: var(--radius-xl);
}

.delete-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 24px;
}

.delete-icon {
  width: 56px;
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--danger-muted);
  border: 1px solid var(--danger-muted);
  border-radius: 50%;
  color: var(--danger);
}

.delete-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.delete-content {
  text-align: center;
  padding: 0 24px 24px;
}

.delete-content p {
  color: var(--text-secondary);
  margin: 0;
}

.delete-content p strong {
  color: var(--text-primary);
}

.warning-text {
  color: var(--danger) !important;
  font-size: 13px;
  margin-top: 8px !important;
}

.delete-footer {
  display: flex;
  justify-content: center;
  gap: 12px;
  padding: 16px 24px;
  background: var(--bg-tertiary);
  border-top: 1px solid var(--border-subtle);
}

/* 响应式 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    padding: 16px;
  }

  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .page-main {
    padding: 16px;
  }

  .provider-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>
