import {useEffect, useState} from 'react'
import {useNavigate} from 'react-router-dom'
import Navbar from '../components/Navbar'
import {
    CheckCircle,
    Database,
    Edit2,
    Loader2,
    Plus,
    Settings,
    Shield,
    Sliders,
    Trash2,
    Users,
    XCircle
} from 'lucide-react'
import {authApi, type User} from '../api/auth'
import {type AIConfig, aiConfigApi, type ModelInfo} from '../api/aiConfig'

export default function AdminPage() {
  const [user, setUser] = useState<User | null>(null)
  const [loading, setLoading] = useState(true)
  const [activeTab, setActiveTab] = useState<'ai' | 'characters' | 'presets' | 'users'>('ai')
  const navigate = useNavigate()

  useEffect(() => {
    loadUserInfo()
  }, [])

  const loadUserInfo = async () => {
    try {
      const response = await authApi.getUserInfo()
      setUser(response.data)

      // 检查是否为管理员
      if (!response.data.isAdmin) {
        alert('无权访问管理后台')
        navigate('/')
      }
    } catch (err) {
      console.error('获取用户信息失败:', err)
      navigate('/login')
    } finally {
      setLoading(false)
    }
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-[#0A0A0F] via-[#1A0B2E] to-[#0A0A0F] flex items-center justify-center">
        <div className="text-white">加载中...</div>
      </div>
    )
  }

  if (!user?.isAdmin) {
    return null
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-[#0A0A0F] via-[#1A0B2E] to-[#0A0A0F]">
      <Navbar />

      <div className="pt-32 pb-20 px-4">
        <div className="max-w-7xl mx-auto">
          <div className="flex items-center gap-3 mb-8">
            <Shield className="w-8 h-8 text-primary" />
            <div>
              <h1 className="text-4xl font-bold">管理后台</h1>
              <p className="text-white/60">系统配置与管理</p>
            </div>
          </div>

          <div className="glass rounded-2xl p-2 mb-8 inline-flex gap-2">
            <button
              onClick={() => setActiveTab('ai')}
              className={`px-6 py-2 rounded-lg text-sm cursor-pointer transition-all flex items-center gap-2 ${
                activeTab === 'ai' ? 'bg-gradient-to-r from-primary to-secondary' : 'hover:bg-white/5'
              }`}
            >
              <Settings className="w-4 h-4" />
              AI 配置
            </button>
            <button
              onClick={() => setActiveTab('characters')}
              className={`px-6 py-2 rounded-lg text-sm cursor-pointer transition-all flex items-center gap-2 ${
                activeTab === 'characters' ? 'bg-gradient-to-r from-primary to-secondary' : 'hover:bg-white/5'
              }`}
            >
              <Users className="w-4 h-4" />
              角色卡管理
            </button>
            <button
              onClick={() => setActiveTab('presets')}
              className={`px-6 py-2 rounded-lg text-sm cursor-pointer transition-all flex items-center gap-2 ${
                activeTab === 'presets' ? 'bg-gradient-to-r from-primary to-secondary' : 'hover:bg-white/5'
              }`}
            >
              <Sliders className="w-4 h-4" />
              预设管理
            </button>
            <button
              onClick={() => setActiveTab('users')}
              className={`px-6 py-2 rounded-lg text-sm cursor-pointer transition-all flex items-center gap-2 ${
                activeTab === 'users' ? 'bg-gradient-to-r from-primary to-secondary' : 'hover:bg-white/5'
              }`}
            >
              <Database className="w-4 h-4" />
              用户管理
            </button>
          </div>

          {activeTab === 'ai' && <AIConfigSection />}
          {activeTab === 'characters' && <CharactersManageSection />}
          {activeTab === 'presets' && <PresetsManageSection />}
          {activeTab === 'users' && <UsersManageSection />}
        </div>
      </div>
    </div>
  )
}

// AI 配置部分
function AIConfigSection() {
  const [configs, setConfigs] = useState<AIConfig[]>([])
  const [loading, setLoading] = useState(true)
  const [_showAddModal, setShowAddModal] = useState(false)
  const [editingConfig, setEditingConfig] = useState<AIConfig | null>(null)
  const [testingConfig, setTestingConfig] = useState<number | null>(null)
  const [testResult, setTestResult] = useState<{ success: boolean; message: string; latency: number } | null>(null)

  useEffect(() => {
    loadConfigs()
  }, [])

  const loadConfigs = async () => {
    try {
      const response = await aiConfigApi.getAIConfigList()
      // 后端返回的是 { list: [], total: number } 结构
      setConfigs(response.data.list || [])
    } catch (err) {
      console.error('加载AI配置失败:', err)
      setConfigs([]) // 确保出错时也设置为空数组
    } finally {
      setLoading(false)
    }
  }

  const handleDelete = async (id: number) => {
    if (!confirm('确定要删除这个AI配置吗？')) return

    try {
      await aiConfigApi.deleteAIConfig(id)
      await loadConfigs()
    } catch (err) {
      console.error('删除失败:', err)
      alert('删除失败')
    }
  }

  const handleTest = async (config: AIConfig) => {
    setTestingConfig(config.id)
    setTestResult(null)

    try {
      // 使用 ID 测试，后端会从数据库获取完整的 API Key
      const response = await aiConfigApi.testAIConfigById(config.id)
      setTestResult(response.data)
    } catch (err: any) {
      setTestResult({
        success: false,
        message: err.response?.data?.msg || '测试失败',
        latency: 0,
      })
    } finally {
      setTestingConfig(null)
    }
  }

  if (loading) {
    return <div className="text-center py-8">加载中...</div>
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold">AI 配置管理</h2>
          <p className="text-white/60 text-sm mt-1">管理 OpenAI、Anthropic 和自定义 AI 服务配置</p>
        </div>
        <button
          onClick={() => setShowAddModal(true)}
          className="px-4 py-2 bg-gradient-to-r from-primary to-secondary rounded-xl font-medium hover:opacity-90 transition-opacity cursor-pointer flex items-center gap-2"
        >
          <Plus className="w-4 h-4" />
          添加配置
        </button>
      </div>

      {configs.length === 0 ? (
        <div className="glass rounded-2xl p-12 text-center">
          <Settings className="w-12 h-12 text-white/40 mx-auto mb-4" />
          <p className="text-white/60 mb-4">还没有AI配置</p>
          <button
            onClick={() => setShowAddModal(true)}
            className="px-6 py-3 bg-gradient-to-r from-primary to-secondary rounded-xl font-medium hover:opacity-90 transition-opacity cursor-pointer"
          >
            添加第一个配置
          </button>
        </div>
      ) : (
        <div className="grid gap-4">
          {configs.map((config) => (
            <div key={config.id} className="glass rounded-2xl p-6">
              <div className="flex items-start justify-between mb-4">
                <div className="flex-1">
                  <div className="flex items-center gap-3 mb-2">
                    <h3 className="text-lg font-semibold">{config.name}</h3>
                    {config.isDefault && (
                      <span className="px-2 py-1 bg-primary/20 text-primary text-xs rounded-lg">默认</span>
                    )}
                    {config.isActive ? (
                      <span className="px-2 py-1 bg-green-500/20 text-green-400 text-xs rounded-lg flex items-center gap-1">
                        <CheckCircle className="w-3 h-3" />
                        启用
                      </span>
                    ) : (
                      <span className="px-2 py-1 bg-white/10 text-white/60 text-xs rounded-lg">禁用</span>
                    )}
                  </div>
                  <div className="space-y-1 text-sm text-white/60">
                    <p>提供商: <span className="text-white/80">{config.provider}</span></p>
                    <p>Base URL: <span className="text-white/80">{config.baseUrl}</span></p>
                    <p>默认模型: <span className="text-white/80">{config.defaultModel}</span></p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => handleTest(config)}
                    disabled={testingConfig === config.id}
                    className="p-2 glass-hover rounded-lg text-sm cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                    title="测试连接"
                  >
                    {testingConfig === config.id ? (
                      <Loader2 className="w-4 h-4 animate-spin" />
                    ) : (
                      <CheckCircle className="w-4 h-4" />
                    )}
                  </button>
                  <button
                    onClick={() => setEditingConfig(config)}
                    className="p-2 glass-hover rounded-lg text-sm cursor-pointer"
                    title="编辑"
                  >
                    <Edit2 className="w-4 h-4" />
                  </button>
                  <button
                    onClick={() => handleDelete(config.id)}
                    className="p-2 glass-hover rounded-lg text-sm cursor-pointer text-red-400 hover:text-red-300"
                    title="删除"
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              </div>

              {testResult && testingConfig === null && (
                <div className={`mt-4 p-3 rounded-lg ${testResult.success ? 'bg-green-500/10 border border-green-500/20' : 'bg-red-500/10 border border-red-500/20'}`}>
                  <div className="flex items-center gap-2 text-sm">
                    {testResult.success ? (
                      <CheckCircle className="w-4 h-4 text-green-400" />
                    ) : (
                      <XCircle className="w-4 h-4 text-red-400" />
                    )}
                    <span className={testResult.success ? 'text-green-400' : 'text-red-400'}>
                      {testResult.message}
                    </span>
                    {testResult.success && (
                      <span className="text-white/60 ml-auto">延迟: {testResult.latency}ms</span>
                    )}
                  </div>
                </div>
              )}
            </div>
          ))}
        </div>
      )}

      {(_showAddModal || editingConfig) && (
        <AIConfigModal
          config={editingConfig}
          onClose={() => {
            setShowAddModal(false)
            setEditingConfig(null)
          }}
          onSuccess={() => {
            setShowAddModal(false)
            setEditingConfig(null)
            loadConfigs()
          }}
        />
      )}
    </div>
  )
}

// AI配置模态框
function AIConfigModal({ config, onClose, onSuccess }: {
  config: AIConfig | null
  onClose: () => void
  onSuccess: () => void
}) {
  const [formData, setFormData] = useState({
    name: config?.name || '',
    provider: config?.provider || 'openai' as 'openai' | 'anthropic' | 'custom',
    baseUrl: config?.baseUrl || 'https://api.openai.com/v1',
    apiKey: config?.apiKey || '',
    defaultModel: config?.defaultModel || '',
    isActive: config?.isActive ?? true,
    isDefault: config?.isDefault ?? false,
  })
  const [models, setModels] = useState<ModelInfo[]>([])
  const [loadingModels, setLoadingModels] = useState(false)
  const [testResult, setTestResult] = useState<{ success: boolean; message: string; latency: number } | null>(null)
  const [testing, setTesting] = useState(false)
  const [saving, setSaving] = useState(false)

  const handleFetchModels = async () => {
    // 如果是编辑已有配置，使用配置ID获取模型列表（使用数据库中的完整API Key）
    if (config?.id) {
      setLoadingModels(true)
      try {
        const response = await aiConfigApi.getModelsByConfigId(config.id)
        setModels(response.data.models || [])
        if (response.data.models && response.data.models.length > 0 && !formData.defaultModel) {
          setFormData({ ...formData, defaultModel: response.data.models[0].id })
        }
      } catch (err: any) {
        console.error('获取模型列表失败:', err)
        setModels([])
        alert(err.response?.data?.msg || '获取模型列表失败，请检查配置是否正确')
      } finally {
        setLoadingModels(false)
      }
      return
    }

    // 新建配置时，使用表单中的信息获取模型列表
    if (!formData.baseUrl || !formData.apiKey) {
      alert('请先填写 Base URL 和 API Key')
      return
    }

    setLoadingModels(true)
    try {
      const response = await aiConfigApi.getModels({
        baseUrl: formData.baseUrl,
        apiKey: formData.apiKey,
        provider: formData.provider,
      })
      setModels(response.data.models || [])
      if (response.data.models && response.data.models.length > 0 && !formData.defaultModel) {
        setFormData({ ...formData, defaultModel: response.data.models[0].id })
      }
    } catch (err: any) {
      console.error('获取模型列表失败:', err)
      setModels([])
      alert(err.response?.data?.msg || '获取模型列表失败，请检查 API Key 和 Base URL 是否正确')
    } finally {
      setLoadingModels(false)
    }
  }

  const handleTest = async () => {
    if (!formData.baseUrl || !formData.apiKey || !formData.defaultModel) {
      alert('请先填写完整信息并选择模型')
      return
    }

    setTesting(true)
    setTestResult(null)
    try {
      const response = await aiConfigApi.testAIConfig({
        baseUrl: formData.baseUrl,
        apiKey: formData.apiKey,
        provider: formData.provider,
        model: formData.defaultModel,
      })
      setTestResult(response.data)
    } catch (err: any) {
      setTestResult({
        success: false,
        message: err.response?.data?.msg || '测试失败',
        latency: 0,
      })
    } finally {
      setTesting(false)
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    if (!formData.name || !formData.baseUrl || !formData.apiKey || !formData.defaultModel) {
      alert('请填写完整信息')
      return
    }

    setSaving(true)
    try {
      if (config) {
        await aiConfigApi.updateAIConfig(config.id, formData)
      } else {
        await aiConfigApi.createAIConfig(formData)
      }
      onSuccess()
    } catch (err: any) {
      alert(err.response?.data?.msg || '保存失败')
    } finally {
      setSaving(false)
    }
  }

  return (
    <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
      <div className="glass rounded-2xl p-6 max-w-2xl w-full max-h-[90vh] overflow-y-auto">
        <h2 className="text-2xl font-bold mb-6">{config ? '编辑' : '添加'} AI 配置</h2>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="text-sm text-white/80 mb-2 block">配置名称</label>
            <input
              type="text"
              value={formData.name}
              onChange={(e) => setFormData({ ...formData, name: e.target.value })}
              placeholder="例如: OpenAI GPT-4"
              className="w-full px-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
              required
            />
          </div>

          <div>
            <label className="text-sm text-white/80 mb-2 block">提供商</label>
            <select
              value={formData.provider}
              onChange={(e) => {
                const provider = e.target.value as 'openai' | 'anthropic' | 'custom'
                const defaultUrls = {
                  openai: 'https://api.openai.com/v1',
                  anthropic: 'https://api.anthropic.com',
                  custom: '',
                }
                setFormData({ ...formData, provider, baseUrl: defaultUrls[provider] })
              }}
              className="w-full px-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
            >
              <option value="openai">OpenAI</option>
              <option value="anthropic">Anthropic</option>
              <option value="custom">自定义</option>
            </select>
          </div>

          <div>
            <label className="text-sm text-white/80 mb-2 block">Base URL</label>
            <input
              type="text"
              value={formData.baseUrl}
              onChange={(e) => setFormData({ ...formData, baseUrl: e.target.value })}
              placeholder="https://api.openai.com/v1"
              className="w-full px-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
              required
            />
          </div>

          <div>
            <label className="text-sm text-white/80 mb-2 block">API Key</label>
            <input
              type="password"
              value={formData.apiKey}
              onChange={(e) => setFormData({ ...formData, apiKey: e.target.value })}
              placeholder="sk-..."
              className="w-full px-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
              required
            />
          </div>

          <div>
            <div className="flex items-center justify-between mb-2">
              <label className="text-sm text-white/80">默认模型</label>
              <button
                type="button"
                onClick={handleFetchModels}
                disabled={loadingModels}
                className="px-3 py-1 glass-hover rounded-lg text-xs cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1"
              >
                {loadingModels ? (
                  <>
                    <Loader2 className="w-3 h-3 animate-spin" />
                    获取中...
                  </>
                ) : (
                  '获取模型列表'
                )}
              </button>
            </div>
            {models && models.length > 0 ? (
              <select
                value={formData.defaultModel}
                onChange={(e) => setFormData({ ...formData, defaultModel: e.target.value })}
                className="w-full px-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                required
              >
                <option value="">选择模型</option>
                {models.map((model) => (
                  <option key={model.id} value={model.id}>
                    {model.name || model.id}
                  </option>
                ))}
              </select>
            ) : (
              <input
                type="text"
                value={formData.defaultModel}
                onChange={(e) => setFormData({ ...formData, defaultModel: e.target.value })}
                placeholder="gpt-4"
                className="w-full px-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                required
              />
            )}
          </div>

          <div className="flex items-center gap-4">
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={formData.isActive}
                onChange={(e) => setFormData({ ...formData, isActive: e.target.checked })}
                className="w-4 h-4 rounded border-white/20 bg-white/10 text-primary focus:ring-primary/50"
              />
              <span className="text-sm text-white/80">启用此配置</span>
            </label>
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={formData.isDefault}
                onChange={(e) => setFormData({ ...formData, isDefault: e.target.checked })}
                className="w-4 h-4 rounded border-white/20 bg-white/10 text-primary focus:ring-primary/50"
              />
              <span className="text-sm text-white/80">设为默认配置</span>
            </label>
          </div>

          {testResult && (
            <div className={`p-3 rounded-lg ${testResult.success ? 'bg-green-500/10 border border-green-500/20' : 'bg-red-500/10 border border-red-500/20'}`}>
              <div className="flex items-center gap-2 text-sm">
                {testResult.success ? (
                  <CheckCircle className="w-4 h-4 text-green-400" />
                ) : (
                  <XCircle className="w-4 h-4 text-red-400" />
                )}
                <span className={testResult.success ? 'text-green-400' : 'text-red-400'}>
                  {testResult.message}
                </span>
                {testResult.success && (
                  <span className="text-white/60 ml-auto">延迟: {testResult.latency}ms</span>
                )}
              </div>
            </div>
          )}

          <div className="flex items-center gap-3 pt-4">
            <button
              type="button"
              onClick={handleTest}
              disabled={testing || !formData.baseUrl || !formData.apiKey || !formData.defaultModel}
              className="px-4 py-2 glass-hover rounded-xl text-sm cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
            >
              {testing ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin" />
                  测试中...
                </>
              ) : (
                <>
                  <CheckCircle className="w-4 h-4" />
                  测试连接
                </>
              )}
            </button>
            <button
              type="submit"
              disabled={saving}
              className="flex-1 px-6 py-3 bg-gradient-to-r from-primary to-secondary rounded-xl font-medium hover:opacity-90 transition-opacity cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {saving ? '保存中...' : '保存配置'}
            </button>
            <button
              type="button"
              onClick={onClose}
              className="px-6 py-3 glass-hover rounded-xl font-medium cursor-pointer"
            >
              取消
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}

// 角色卡管理部分
function CharactersManageSection() {
  const [characters, setCharacters] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [stats, setStats] = useState({ total: 0, public: 0, private: 0 })
  const [searchQuery, setSearchQuery] = useState('')
  const [filterPublic, setFilterPublic] = useState<boolean | null>(null)

  useEffect(() => {
    loadCharacters()
    loadStats()
  }, [filterPublic, searchQuery])

  const loadCharacters = async () => {
    try {
      const response = await fetch(`http://localhost:8888/app/character?page=1&pageSize=20&keyword=${searchQuery}${filterPublic !== null ? `&isPublic=${filterPublic}` : ''}`, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      const data = await response.json()
      setCharacters(data.data?.list || [])
    } catch (err) {
      console.error('加载角色卡失败:', err)
    } finally {
      setLoading(false)
    }
  }

  const loadStats = async () => {
    try {
      const response = await fetch('http://localhost:8888/app/character?page=1&pageSize=1', {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      const data = await response.json()
      const total = data.data?.total || 0

      const publicResponse = await fetch('http://localhost:8888/app/character?page=1&pageSize=1&isPublic=true', {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      const publicData = await publicResponse.json()
      const publicCount = publicData.data?.total || 0

      setStats({
        total,
        public: publicCount,
        private: total - publicCount
      })
    } catch (err) {
      console.error('加载统计失败:', err)
    }
  }

  const handleDelete = async (id: number) => {
    if (!confirm('确定要删除这个角色卡吗？')) return

    try {
      await fetch(`http://localhost:8888/app/character/${id}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      loadCharacters()
      loadStats()
    } catch (err) {
      console.error('删除失败:', err)
      alert('删除失败')
    }
  }

  const handleTogglePublic = async (id: number, isPublic: boolean) => {
    try {
      await fetch(`http://localhost:8888/app/character/${id}`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ isPublic: !isPublic })
      })
      loadCharacters()
      loadStats()
    } catch (err) {
      console.error('更新失败:', err)
      alert('更新失败')
    }
  }

  if (loading) {
    return <div className="text-center py-8">加载中...</div>
  }

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-3 gap-4">
        <div className="glass rounded-xl p-4">
          <div className="text-sm text-white/60 mb-1">总角色卡数</div>
          <div className="text-2xl font-bold">{stats.total}</div>
        </div>
        <div className="glass rounded-xl p-4">
          <div className="text-sm text-white/60 mb-1">公开角色卡</div>
          <div className="text-2xl font-bold text-green-400">{stats.public}</div>
        </div>
        <div className="glass rounded-xl p-4">
          <div className="text-sm text-white/60 mb-1">私有角色卡</div>
          <div className="text-2xl font-bold text-blue-400">{stats.private}</div>
        </div>
      </div>

      <div className="glass rounded-2xl p-6">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-xl font-semibold flex items-center gap-2">
            <Users className="w-5 h-5 text-primary" />
            角色卡列表
          </h2>
          <div className="flex items-center gap-2">
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="搜索角色卡..."
              className="px-4 py-2 glass rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
            />
            <select
              value={filterPublic === null ? 'all' : filterPublic ? 'public' : 'private'}
              onChange={(e) => setFilterPublic(e.target.value === 'all' ? null : e.target.value === 'public')}
              className="px-4 py-2 glass rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
            >
              <option value="all">全部</option>
              <option value="public">公开</option>
              <option value="private">私有</option>
            </select>
          </div>
        </div>

        {characters.length === 0 ? (
          <div className="text-center py-12 text-white/60">暂无角色卡</div>
        ) : (
          <div className="space-y-3">
            {characters.map((char) => (
              <div key={char.id} className="glass-hover rounded-xl p-4 flex items-center gap-4">
                {char.avatar && (
                  <img src={char.avatar} alt={char.name} className="w-12 h-12 rounded-lg object-cover" />
                )}
                <div className="flex-1">
                  <div className="flex items-center gap-2 mb-1">
                    <h3 className="font-medium">{char.name}</h3>
                    {char.isPublic ? (
                      <span className="px-2 py-0.5 bg-green-500/20 text-green-400 text-xs rounded">公开</span>
                    ) : (
                      <span className="px-2 py-0.5 bg-white/10 text-white/60 text-xs rounded">私有</span>
                    )}
                  </div>
                  <p className="text-sm text-white/60 line-clamp-1">{char.description}</p>
                  <div className="flex items-center gap-4 mt-2 text-xs text-white/40">
                    <span>使用次数: {char.useCount}</span>
                    <span>收藏: {char.favoriteCount}</span>
                    <span>创建者: {char.creator}</span>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => handleTogglePublic(char.id, char.isPublic)}
                    className="px-3 py-1 glass-hover rounded-lg text-sm cursor-pointer"
                  >
                    {char.isPublic ? '设为私有' : '设为公开'}
                  </button>
                  <button
                    onClick={() => handleDelete(char.id)}
                    className="px-3 py-1 glass-hover rounded-lg text-sm cursor-pointer text-red-400 hover:text-red-300"
                  >
                    删除
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}

// 预设管理部分
function PresetsManageSection() {
  const [presets, setPresets] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [_showAddModal, setShowAddModal] = useState(false)
  const [_editingPreset, setEditingPreset] = useState<any>(null)

  useEffect(() => {
    loadPresets()
  }, [])

  const loadPresets = async () => {
    try {
      const response = await fetch('http://localhost:8888/app/preset?page=1&pageSize=50', {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      const data = await response.json()
      setPresets(data.data?.list || [])
    } catch (err) {
      console.error('加载预设失败:', err)
    } finally {
      setLoading(false)
    }
  }

  const handleDelete = async (id: number) => {
    if (!confirm('确定要删除这个预设吗？')) return

    try {
      await fetch(`http://localhost:8888/app/preset/${id}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      loadPresets()
    } catch (err) {
      console.error('删除失败:', err)
      alert('删除失败')
    }
  }

  if (loading) {
    return <div className="text-center py-8">加载中...</div>
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold">预设管理</h2>
          <p className="text-white/60 text-sm mt-1">管理对话预设配置</p>
        </div>
        <button
          onClick={() => setShowAddModal(true)}
          className="px-4 py-2 bg-gradient-to-r from-primary to-secondary rounded-xl font-medium hover:opacity-90 transition-opacity cursor-pointer flex items-center gap-2"
        >
          <Plus className="w-4 h-4" />
          添加预设
        </button>
      </div>

      {presets.length === 0 ? (
        <div className="glass rounded-2xl p-12 text-center">
          <Sliders className="w-12 h-12 text-white/40 mx-auto mb-4" />
          <p className="text-white/60 mb-4">还没有预设配置</p>
          <button
            onClick={() => setShowAddModal(true)}
            className="px-6 py-3 bg-gradient-to-r from-primary to-secondary rounded-xl font-medium hover:opacity-90 transition-opacity cursor-pointer"
          >
            添加第一个预设
          </button>
        </div>
      ) : (
        <div className="grid gap-4">
          {presets.map((preset) => (
            <div key={preset.id} className="glass rounded-2xl p-6">
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <div className="flex items-center gap-3 mb-2">
                    <h3 className="text-lg font-semibold">{preset.name}</h3>
                    {preset.isDefault && (
                      <span className="px-2 py-1 bg-primary/20 text-primary text-xs rounded-lg">默认</span>
                    )}
                  </div>
                  <p className="text-sm text-white/60 mb-3">{preset.description}</p>
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">
                    <div>
                      <span className="text-white/40">Temperature:</span>
                      <span className="ml-2 text-white/80">{preset.temperature}</span>
                    </div>
                    <div>
                      <span className="text-white/40">Max Tokens:</span>
                      <span className="ml-2 text-white/80">{preset.maxTokens}</span>
                    </div>
                    <div>
                      <span className="text-white/40">Top P:</span>
                      <span className="ml-2 text-white/80">{preset.topP}</span>
                    </div>
                    <div>
                      <span className="text-white/40">Frequency Penalty:</span>
                      <span className="ml-2 text-white/80">{preset.frequencyPenalty}</span>
                    </div>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => setEditingPreset(preset)}
                    className="p-2 glass-hover rounded-lg text-sm cursor-pointer"
                    title="编辑"
                  >
                    <Edit2 className="w-4 h-4" />
                  </button>
                  <button
                    onClick={() => handleDelete(preset.id)}
                    className="p-2 glass-hover rounded-lg text-sm cursor-pointer text-red-400 hover:text-red-300"
                    title="删除"
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}

// 用户管理部分
function UsersManageSection() {
  const [users, setUsers] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [stats, setStats] = useState({ total: 0, active: 0, inactive: 0, admins: 0 })
  const [searchQuery, setSearchQuery] = useState('')

  useEffect(() => {
    loadUsers()
  }, [searchQuery])

  const loadUsers = async () => {
    try {
      // 注意：这里需要后端提供管理员用户列表接口
      // 暂时使用模拟数据
      const mockUsers = [
        {
          id: 1,
          username: 'admin',
          nickName: '管理员',
          email: 'admin@example.com',
          isAdmin: true,
          enable: true,
          chatCount: 150,
          messageCount: 3200,
          lastLoginAt: '2024-01-15T10:30:00Z',
          createdAt: '2024-01-01T00:00:00Z'
        }
      ]
      setUsers(mockUsers)
      setStats({
        total: mockUsers.length,
        active: mockUsers.filter(u => u.enable).length,
        inactive: mockUsers.filter(u => !u.enable).length,
        admins: mockUsers.filter(u => u.isAdmin).length
      })
    } catch (err) {
      console.error('加载用户失败:', err)
    } finally {
      setLoading(false)
    }
  }

  const handleToggleStatus = async (_id: number, _enable: boolean) => {
    if (!confirm(`确定要${_enable ? '禁用' : '启用'}这个用户吗？`)) return

    try {
      // 需要后端提供更新用户状态的接口
      alert('功能开发中')
    } catch (err) {
      console.error('更新失败:', err)
      alert('更新失败')
    }
  }

  const handleToggleAdmin = async (_id: number, _isAdmin: boolean) => {
    if (!confirm(`确定要${_isAdmin ? '移除' : '授予'}管理员权限吗？`)) return

    try {
      // 需要后端提供更新用户权限的接口
      alert('功能开发中')
    } catch (err) {
      console.error('更新失败:', err)
      alert('更新失败')
    }
  }

  if (loading) {
    return <div className="text-center py-8">加载中...</div>
  }

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-4 gap-4">
        <div className="glass rounded-xl p-4">
          <div className="text-sm text-white/60 mb-1">总用户数</div>
          <div className="text-2xl font-bold">{stats.total}</div>
        </div>
        <div className="glass rounded-xl p-4">
          <div className="text-sm text-white/60 mb-1">活跃用户</div>
          <div className="text-2xl font-bold text-green-400">{stats.active}</div>
        </div>
        <div className="glass rounded-xl p-4">
          <div className="text-sm text-white/60 mb-1">禁用用户</div>
          <div className="text-2xl font-bold text-red-400">{stats.inactive}</div>
        </div>
        <div className="glass rounded-xl p-4">
          <div className="text-sm text-white/60 mb-1">管理员</div>
          <div className="text-2xl font-bold text-primary">{stats.admins}</div>
        </div>
      </div>

      <div className="glass rounded-2xl p-6">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-xl font-semibold flex items-center gap-2">
            <Database className="w-5 h-5 text-primary" />
            用户列表
          </h2>
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="搜索用户..."
            className="px-4 py-2 glass rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
          />
        </div>

        {users.length === 0 ? (
          <div className="text-center py-12 text-white/60">暂无用户</div>
        ) : (
          <div className="space-y-3">
            {users.map((user) => (
              <div key={user.id} className="glass-hover rounded-xl p-4">
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-2">
                      <h3 className="font-medium">{user.nickName || user.username}</h3>
                      <span className="text-sm text-white/40">@{user.username}</span>
                      {user.isAdmin && (
                        <span className="px-2 py-0.5 bg-primary/20 text-primary text-xs rounded">管理员</span>
                      )}
                      {user.enable ? (
                        <span className="px-2 py-0.5 bg-green-500/20 text-green-400 text-xs rounded">活跃</span>
                      ) : (
                        <span className="px-2 py-0.5 bg-red-500/20 text-red-400 text-xs rounded">禁用</span>
                      )}
                    </div>
                    <div className="text-sm text-white/60 mb-2">{user.email}</div>
                    <div className="flex items-center gap-4 text-xs text-white/40">
                      <span>对话数: {user.chatCount}</span>
                      <span>消息数: {user.messageCount}</span>
                      <span>最后登录: {user.lastLoginAt ? new Date(user.lastLoginAt).toLocaleString('zh-CN') : '从未登录'}</span>
                      <span>注册时间: {new Date(user.createdAt).toLocaleString('zh-CN')}</span>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <button
                      onClick={() => handleToggleAdmin(user.id, user.isAdmin)}
                      className="px-3 py-1 glass-hover rounded-lg text-sm cursor-pointer"
                    >
                      {user.isAdmin ? '移除管理员' : '设为管理员'}
                    </button>
                    <button
                      onClick={() => handleToggleStatus(user.id, user.enable)}
                      className={`px-3 py-1 glass-hover rounded-lg text-sm cursor-pointer ${
                        user.enable ? 'text-red-400 hover:text-red-300' : 'text-green-400 hover:text-green-300'
                      }`}
                    >
                      {user.enable ? '禁用' : '启用'}
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      <div className="glass rounded-2xl p-6">
        <h3 className="text-lg font-semibold mb-4">用户统计</h3>
        <div className="text-sm text-white/60">
          <p className="mb-2">注意：用户管理功能需要后端提供以下接口：</p>
          <ul className="list-disc list-inside space-y-1 ml-2">
            <li>GET /admin/users - 获取用户列表</li>
            <li>PUT /admin/users/:id/status - 更新用户状态（启用/禁用）</li>
            <li>PUT /admin/users/:id/admin - 更新管理员权限</li>
          </ul>
        </div>
      </div>
    </div>
  )
}
