import {useEffect, useState} from 'react'
import Navbar from '../components/Navbar'
import {Check, Copy, Download, Edit, FileJson, Plus, Search, Star, Trash2, Upload} from 'lucide-react'
import {type Preset, presetApi} from '../api/preset'

export default function PresetManagePage() {
  const [presets, setPresets] = useState<Preset[]>([])
  const [searchQuery, setSearchQuery] = useState('')
  const [showUploadModal, setShowUploadModal] = useState(false)
  const [showEditModal, setShowEditModal] = useState(false)
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [selectedPreset, setSelectedPreset] = useState<Preset | null>(null)
  const [copiedId, setCopiedId] = useState<number | null>(null)
  const [loading, setLoading] = useState(true)
  const [page, setPage] = useState(1)
  const [total, setTotal] = useState(0)

  // 加载预设列表
  useEffect(() => {
    loadPresets()
  }, [page, searchQuery])

  const loadPresets = async () => {
    try {
      setLoading(true)
      const response = await presetApi.getPresetList({
        page,
        pageSize: 20,
        keyword: searchQuery
      })
      setPresets(response.data.list)
      setTotal(response.data.total)
    } catch (err) {
      console.error('加载预设失败:', err)
      alert('加载预设失败，请重试')
    } finally {
      setLoading(false)
    }
  }

  // 文件上传导入
  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return

    try {
      await presetApi.importPreset(file)
      await loadPresets()
      setShowUploadModal(false)
      alert('预设导入成功！')
    } catch (err: any) {
      console.error('导入预设失败:', err)
      alert(err.response?.data?.msg || '导入失败，请检查文件格式')
    }
  }

  // 导出预设
  const handleExport = async (preset: Preset) => {
    try {
      const response = await presetApi.exportPreset(preset.id)
      const blob = new Blob([response.data], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `${preset.name}.json`
      a.click()
      URL.revokeObjectURL(url)
    } catch (err) {
      console.error('导出预设失败:', err)
      alert('导出失败，请重试')
    }
  }

  // 复制预设
  const handleCopy = async (preset: Preset) => {
    try {
      await presetApi.createPreset({
        name: `${preset.name} (副本)`,
        description: preset.description,
        temperature: preset.temperature,
        topP: preset.topP,
        topK: preset.topK,
        frequencyPenalty: preset.frequencyPenalty,
        presencePenalty: preset.presencePenalty,
        maxTokens: preset.maxTokens,
        repetitionPenalty: preset.repetitionPenalty,
        minP: preset.minP,
        topA: preset.topA,
        systemPrompt: preset.systemPrompt,
        stopSequences: preset.stopSequences,
        extensions: preset.extensions
      })
      await loadPresets()
      setCopiedId(preset.id)
      setTimeout(() => setCopiedId(null), 2000)
    } catch (err) {
      console.error('复制预设失败:', err)
      alert('复制失败，请重试')
    }
  }

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

    try {
      await presetApi.deletePreset(id)
      await loadPresets()
    } catch (err: any) {
      console.error('删除预设失败:', err)
      alert(err.response?.data?.msg || '删除失败，请重试')
    }
  }

  // 设置默认预设
  const handleSetDefault = async (id: number) => {
    try {
      await presetApi.setDefaultPreset(id)
      await loadPresets()
      alert('已设置为默认预设')
    } catch (err) {
      console.error('设置默认预设失败:', err)
      alert('设置失败，请重试')
    }
  }

  // 保存编辑
  const handleSaveEdit = async (updatedPreset: Preset) => {
    try {
      await presetApi.updatePreset(updatedPreset.id, {
        name: updatedPreset.name,
        description: updatedPreset.description,
        temperature: updatedPreset.temperature,
        topP: updatedPreset.topP,
        topK: updatedPreset.topK,
        frequencyPenalty: updatedPreset.frequencyPenalty,
        presencePenalty: updatedPreset.presencePenalty,
        maxTokens: updatedPreset.maxTokens,
        repetitionPenalty: updatedPreset.repetitionPenalty,
        minP: updatedPreset.minP,
        topA: updatedPreset.topA,
        systemPrompt: updatedPreset.systemPrompt,
        stopSequences: updatedPreset.stopSequences,
        extensions: updatedPreset.extensions
      })
      await loadPresets()
      setShowEditModal(false)
      alert('保存成功')
    } catch (err) {
      console.error('保存预设失败:', err)
      alert('保存失败，请重试')
    }
  }

  // 创建新预设
  const handleCreate = async (newPreset: Partial<Preset>) => {
    try {
      await presetApi.createPreset({
        name: newPreset.name!,
        description: newPreset.description,
        temperature: newPreset.temperature ?? 0.7,
        topP: newPreset.topP ?? 0.9,
        topK: newPreset.topK ?? 40,
        frequencyPenalty: newPreset.frequencyPenalty ?? 0,
        presencePenalty: newPreset.presencePenalty ?? 0,
        maxTokens: newPreset.maxTokens ?? 2048,
        repetitionPenalty: newPreset.repetitionPenalty ?? 1.0,
        minP: newPreset.minP ?? 0,
        topA: newPreset.topA ?? 0,
        systemPrompt: newPreset.systemPrompt ?? '',
        stopSequences: newPreset.stopSequences ?? [],
        extensions: newPreset.extensions ?? {}
      })
      await loadPresets()
      setShowCreateModal(false)
      alert('创建成功')
    } catch (err) {
      console.error('创建预设失败:', err)
      alert('创建失败，请重试')
    }
  }

  const filteredPresets = presets

  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 justify-between mb-8">
            <div>
              <h1 className="text-4xl font-bold mb-2">预设管理</h1>
              <p className="text-white/60">管理对话预设参数</p>
            </div>
            <div className="flex gap-3">
              <button
                onClick={() => setShowCreateModal(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 flex items-center gap-2"
              >
                <Plus className="w-5 h-5" />
                新建预设
              </button>
              <button
                onClick={() => setShowUploadModal(true)}
                className="px-6 py-3 glass-hover rounded-xl font-medium cursor-pointer flex items-center gap-2"
              >
                <Upload className="w-5 h-5" />
                导入预设
              </button>
            </div>
          </div>

          <div className="glass rounded-2xl p-6 mb-8">
            <div className="relative">
              <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-white/40" />
              <input
                type="text"
                placeholder="搜索预设名称或描述..."
                value={searchQuery}
                onChange={(e) => {
                  setSearchQuery(e.target.value)
                  setPage(1)
                }}
                className="w-full pl-12 pr-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
              />
            </div>
          </div>

          {loading ? (
            <div className="text-center text-white/60 py-12">加载中...</div>
          ) : filteredPresets.length === 0 ? (
            <div className="text-center text-white/60 py-12">
              <p className="mb-2">还没有预设</p>
              <p className="text-sm">创建或导入一个预设开始使用吧！</p>
            </div>
          ) : (
            <div className="grid md:grid-cols-2 gap-6">
              {filteredPresets.map((preset) => (
                <div key={preset.id} className="glass-hover rounded-2xl p-6">
                  <div className="flex items-start justify-between mb-4">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        <h3 className="text-lg font-semibold">{preset.name}</h3>
                        {preset.isDefault && (
                          <span className="text-xs px-2 py-1 bg-primary/20 text-primary rounded flex items-center gap-1">
                            <Star className="w-3 h-3" />
                            默认
                          </span>
                        )}
                        {preset.isPublic && (
                          <span className="text-xs px-2 py-1 bg-secondary/20 text-secondary rounded">
                            公开
                          </span>
                        )}
                      </div>
                      <p className="text-sm text-white/60">{preset.description}</p>
                      <p className="text-xs text-white/40 mt-2">使用次数: {preset.useCount}</p>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-3 mb-4 text-sm">
                    <div className="glass rounded-lg p-3">
                      <div className="text-white/60 mb-1">温度</div>
                      <div className="font-medium">{preset.temperature}</div>
                    </div>
                    <div className="glass rounded-lg p-3">
                      <div className="text-white/60 mb-1">最大令牌</div>
                      <div className="font-medium">{preset.maxTokens}</div>
                    </div>
                    <div className="glass rounded-lg p-3">
                      <div className="text-white/60 mb-1">Top P</div>
                      <div className="font-medium">{preset.topP}</div>
                    </div>
                    <div className="glass rounded-lg p-3">
                      <div className="text-white/60 mb-1">Top K</div>
                      <div className="font-medium">{preset.topK}</div>
                    </div>
                  </div>

                  <div className="flex gap-2">
                    <button
                      onClick={() => {
                        setSelectedPreset(preset)
                        setShowEditModal(true)
                      }}
                      className="flex-1 px-4 py-2 glass-hover rounded-lg text-sm cursor-pointer flex items-center justify-center gap-2"
                    >
                      <Edit className="w-4 h-4" />
                      编辑
                    </button>
                    {!preset.isDefault && (
                      <button
                        onClick={() => handleSetDefault(preset.id)}
                        className="px-4 py-2 glass-hover rounded-lg text-sm cursor-pointer"
                        title="设为默认"
                      >
                        <Star className="w-4 h-4" />
                      </button>
                    )}
                    <button
                      onClick={() => handleCopy(preset)}
                      className="px-4 py-2 glass-hover rounded-lg text-sm cursor-pointer"
                      title="复制预设"
                    >
                      {copiedId === preset.id ? (
                        <Check className="w-4 h-4 text-green-400" />
                      ) : (
                        <Copy className="w-4 h-4" />
                      )}
                    </button>
                    <button
                      onClick={() => handleExport(preset)}
                      className="px-4 py-2 glass-hover rounded-lg text-sm cursor-pointer"
                      title="导出预设"
                    >
                      <Download className="w-4 h-4" />
                    </button>
                    <button
                      onClick={() => handleDelete(preset.id)}
                      className="px-4 py-2 glass-hover rounded-lg text-sm cursor-pointer text-red-400"
                      title="删除预设"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* 分页 */}
          {total > 20 && (
            <div className="flex justify-center gap-2 mt-8">
              <button
                onClick={() => setPage(p => Math.max(1, p - 1))}
                disabled={page === 1}
                className="px-4 py-2 glass-hover rounded-lg text-sm cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
              >
                上一页
              </button>
              <span className="px-4 py-2 glass rounded-lg text-sm">
                第 {page} 页 / 共 {Math.ceil(total / 20)} 页
              </span>
              <button
                onClick={() => setPage(p => p + 1)}
                disabled={page >= Math.ceil(total / 20)}
                className="px-4 py-2 glass-hover rounded-lg text-sm cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
              >
                下一页
              </button>
            </div>
          )}
        </div>
      </div>

      {/* 导入模态框 */}
      {showUploadModal && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="glass rounded-3xl p-8 max-w-md w-full">
            <h2 className="text-2xl font-bold mb-6">导入预设</h2>

            <div>
              <label className="block text-sm text-white/80 mb-2">JSON 预设文件</label>
              <label className="glass-hover rounded-xl p-6 border-2 border-dashed border-white/20 cursor-pointer block text-center">
                <FileJson className="w-8 h-8 mx-auto mb-2 text-white/40" />
                <span className="text-sm text-white/60">点击上传 JSON 格式预设</span>
                <input
                  type="file"
                  accept=".json"
                  onChange={handleFileUpload}
                  className="hidden"
                />
              </label>
              <p className="text-xs text-white/40 mt-2">
                支持 SillyTavern、TavernAI 等格式的预设文件
              </p>
            </div>

            <button
              onClick={() => setShowUploadModal(false)}
              className="w-full mt-6 px-6 py-3 glass-hover rounded-xl cursor-pointer"
            >
              取消
            </button>
          </div>
        </div>
      )}

      {/* 编辑模态框 */}
      {showEditModal && selectedPreset && (
        <EditPresetModal
          preset={selectedPreset}
          onSave={handleSaveEdit}
          onClose={() => setShowEditModal(false)}
        />
      )}

      {/* 创建模态框 */}
      {showCreateModal && (
        <CreatePresetModal
          onCreate={handleCreate}
          onClose={() => setShowCreateModal(false)}
        />
      )}
    </div>
  )
}

// 编辑预设模态框
function EditPresetModal({ preset, onSave, onClose }: {
  preset: Preset
  onSave: (preset: Preset) => void
  onClose: () => void
}) {
  // 解析 extensions 中的 prompts
  const getPrompts = () => {
    const ext = preset.extensions as any
    if (ext?.prompts && Array.isArray(ext.prompts)) {
      return ext.prompts
    }
    // 默认提示词结构
    return [
      { identifier: 'main', name: 'Main Prompt', content: '', role: 'system', system_prompt: true },
      { identifier: 'nsfw', name: 'Auxiliary Prompt', content: '', role: 'system', system_prompt: true },
      { identifier: 'jailbreak', name: 'Post-History Instructions', content: '', role: 'system', system_prompt: true },
    ]
  }

  const [formData, setFormData] = useState({
    ...preset,
    description: preset.description || '',
    temperature: preset.temperature ?? 0.7,
    maxTokens: preset.maxTokens ?? 2048,
    topP: preset.topP ?? 0.9,
    topK: preset.topK ?? 40,
    frequencyPenalty: preset.frequencyPenalty ?? 0,
    presencePenalty: preset.presencePenalty ?? 0,
    repetitionPenalty: preset.repetitionPenalty ?? 1.0,
    minP: preset.minP ?? 0,
    topA: preset.topA ?? 0,
    systemPrompt: preset.systemPrompt || '',
    stopSequences: preset.stopSequences || [],
    extensions: preset.extensions || {}
  })

  const [prompts, setPrompts] = useState(getPrompts())
  const [activeTab, setActiveTab] = useState<'params' | 'prompts'>('params')

  const handlePromptChange = (index: number, field: string, value: any) => {
    const newPrompts = [...prompts]
    newPrompts[index] = { ...newPrompts[index], [field]: value }
    setPrompts(newPrompts)
  }

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

    // 更新 extensions 中的 prompts
    const updatedExtensions = {
      ...(formData.extensions as any),
      prompts: prompts
    }

    onSave({
      ...formData,
      extensions: updatedExtensions
    })
  }

  return (
    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4 overflow-y-auto">
      <div className="glass rounded-3xl p-8 max-w-4xl w-full my-8">
        <h2 className="text-2xl font-bold mb-6">编辑预设</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 })}
              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>
            <input
              type="text"
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: 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"
            />
          </div>

          {/* 标签页切换 */}
          <div className="flex gap-2 border-b border-white/10">
            <button
              type="button"
              onClick={() => setActiveTab('params')}
              className={`px-4 py-2 text-sm font-medium transition-colors ${
                activeTab === 'params'
                  ? 'text-primary border-b-2 border-primary'
                  : 'text-white/60 hover:text-white/80'
              }`}
            >
              采样参数
            </button>
            <button
              type="button"
              onClick={() => setActiveTab('prompts')}
              className={`px-4 py-2 text-sm font-medium transition-colors ${
                activeTab === 'prompts'
                  ? 'text-primary border-b-2 border-primary'
                  : 'text-white/60 hover:text-white/80'
              }`}
            >
              提示词管理
            </button>
          </div>

          <div className="max-h-[50vh] overflow-y-auto pr-2">
            {activeTab === 'params' ? (
              <div className="space-y-4">
                <div className="grid md:grid-cols-2 gap-4">
                  <div>
                    <label className="text-sm text-white/80 mb-2 block">
                      温度 (Temperature): {formData.temperature}
                    </label>
                    <input
                      type="range"
                      min="0"
                      max="2"
                      step="0.1"
                      value={formData.temperature}
                      onChange={(e) => setFormData({ ...formData, temperature: parseFloat(e.target.value) })}
                      className="w-full"
                    />
                    <p className="text-xs text-white/40 mt-1">控制输出的随机性</p>
                  </div>

                  <div>
                    <label className="text-sm text-white/80 mb-2 block">
                      最大令牌 (Max Tokens): {formData.maxTokens}
                    </label>
                    <input
                      type="number"
                      value={formData.maxTokens}
                      onChange={(e) => setFormData({ ...formData, maxTokens: parseInt(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"
                      min="1"
                      max="32000"
                    />
                  </div>

                  <div>
                    <label className="text-sm text-white/80 mb-2 block">
                      Top P: {formData.topP}
                    </label>
                    <input
                      type="range"
                      min="0"
                      max="1"
                      step="0.05"
                      value={formData.topP}
                      onChange={(e) => setFormData({ ...formData, topP: parseFloat(e.target.value) })}
                      className="w-full"
                    />
                  </div>

                  <div>
                    <label className="text-sm text-white/80 mb-2 block">
                      Top K: {formData.topK}
                    </label>
                    <input
                      type="number"
                      value={formData.topK}
                      onChange={(e) => setFormData({ ...formData, topK: parseInt(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"
                      min="0"
                      max="100"
                    />
                  </div>

                  <div>
                    <label className="text-sm text-white/80 mb-2 block">
                      频率惩罚: {formData.frequencyPenalty}
                    </label>
                    <input
                      type="range"
                      min="-2"
                      max="2"
                      step="0.1"
                      value={formData.frequencyPenalty}
                      onChange={(e) => setFormData({ ...formData, frequencyPenalty: parseFloat(e.target.value) })}
                      className="w-full"
                    />
                  </div>

                  <div>
                    <label className="text-sm text-white/80 mb-2 block">
                      存在惩罚: {formData.presencePenalty}
                    </label>
                    <input
                      type="range"
                      min="-2"
                      max="2"
                      step="0.1"
                      value={formData.presencePenalty}
                      onChange={(e) => setFormData({ ...formData, presencePenalty: parseFloat(e.target.value) })}
                      className="w-full"
                    />
                  </div>
                </div>

                <div>
                  <label className="text-sm text-white/80 mb-2 block">停止序列（每行一个）</label>
                  <textarea
                    rows={3}
                    value={(formData.stopSequences || []).join('\n')}
                    onChange={(e) => setFormData({ ...formData, stopSequences: e.target.value.split('\n').filter(s => s.trim()) })}
                    className="w-full px-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 resize-none"
                    placeholder="输入停止序列..."
                  />
                </div>
              </div>
            ) : (
              <div className="space-y-3">
                <p className="text-sm text-white/60 mb-4">
                  管理对话提示词的内容和顺序，控制 AI 的行为和响应方式
                </p>
                {prompts.map((prompt: any, index: number) => (
                  <div key={index} className="glass rounded-xl p-4">
                    <div className="flex items-center gap-3 mb-3">
                      <div className="flex items-center gap-2 flex-1">
                        <span className="text-sm font-medium">{prompt.name || prompt.identifier}</span>
                        {prompt.identifier && (
                          <span className="text-xs text-white/40 px-2 py-0.5 glass rounded">
                            {prompt.identifier}
                          </span>
                        )}
                      </div>
                      <label className="flex items-center gap-2 text-sm">
                        <input
                          type="checkbox"
                          checked={!prompt.marker}
                          onChange={(e) => handlePromptChange(index, 'marker', !e.target.checked)}
                          className="rounded"
                        />
                        <span className="text-white/60">启用</span>
                      </label>
                    </div>
                    {!prompt.marker && (
                      <textarea
                        rows={3}
                        value={prompt.content || ''}
                        onChange={(e) => handlePromptChange(index, 'content', e.target.value)}
                        className="w-full px-3 py-2 glass rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 resize-none"
                        placeholder={`输入 ${prompt.name} 的内容...`}
                      />
                    )}
                  </div>
                ))}
              </div>
            )}
          </div>

          <div className="flex gap-3 pt-4">
            <button
              type="button"
              onClick={onClose}
              className="flex-1 px-6 py-3 glass-hover rounded-xl cursor-pointer"
            >
              取消
            </button>
            <button
              type="submit"
              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"
            >
              保存
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}

// 创建预设模态框
function CreatePresetModal({ onCreate, onClose }: {
  onCreate: (preset: Partial<Preset>) => void
  onClose: () => void
}) {
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    temperature: 0.7,
    maxTokens: 2048,
    topP: 0.9,
    topK: 40,
    frequencyPenalty: 0,
    presencePenalty: 0,
    repetitionPenalty: 1.0,
    minP: 0,
    topA: 0,
    systemPrompt: '',
    stopSequences: [] as string[],
    extensions: {} as Record<string, any>
  })

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    onCreate(formData)
  }

  return (
    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4 overflow-y-auto">
      <div className="glass rounded-3xl p-8 max-w-2xl w-full my-8">
        <h2 className="text-2xl font-bold mb-6">创建新预设</h2>

        <form onSubmit={handleSubmit} className="space-y-4 max-h-[60vh] overflow-y-auto pr-2">
          <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 })}
              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>
            <input
              type="text"
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: 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"
            />
          </div>

          <div className="grid md:grid-cols-2 gap-4">
            <div>
              <label className="text-sm text-white/80 mb-2 block">
                温度: {formData.temperature}
              </label>
              <input
                type="range"
                min="0"
                max="2"
                step="0.1"
                value={formData.temperature}
                onChange={(e) => setFormData({ ...formData, temperature: parseFloat(e.target.value) })}
                className="w-full"
              />
            </div>

            <div>
              <label className="text-sm text-white/80 mb-2 block">
                最大令牌: {formData.maxTokens}
              </label>
              <input
                type="number"
                value={formData.maxTokens}
                onChange={(e) => setFormData({ ...formData, maxTokens: parseInt(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"
                min="1"
                max="32000"
              />
            </div>
          </div>

          <div>
            <label className="text-sm text-white/80 mb-2 block">系统提示词</label>
            <textarea
              rows={4}
              value={formData.systemPrompt}
              onChange={(e) => setFormData({ ...formData, systemPrompt: 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 resize-none"
              placeholder="设置 AI 的行为和角色..."
            />
          </div>

          <div>
            <label className="text-sm text-white/80 mb-2 block">停止序列（每行一个）</label>
            <textarea
              rows={3}
              value={formData.stopSequences.join('\n')}
              onChange={(e) => setFormData({ ...formData, stopSequences: e.target.value.split('\n').filter(s => s.trim()) })}
              className="w-full px-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 resize-none"
              placeholder="输入停止序列..."
            />
          </div>

          <div>
            <label className="text-sm text-white/80 mb-2 block">扩展配置（JSON 格式）</label>
            <textarea
              rows={4}
              value={JSON.stringify(formData.extensions, null, 2)}
              onChange={(e) => {
                try {
                  const parsed = JSON.parse(e.target.value)
                  setFormData({ ...formData, extensions: parsed })
                } catch (err) {
                  // 保持原值，等待用户输入完整的 JSON
                }
              }}
              className="w-full px-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 resize-none font-mono"
              placeholder='{"key": "value"}'
            />
            <p className="text-xs text-white/40 mt-1">用于 SillyTavern 扩展配置</p>
          </div>

          <div className="flex gap-3 pt-4">
            <button
              type="button"
              onClick={onClose}
              className="flex-1 px-6 py-3 glass-hover rounded-xl cursor-pointer"
            >
              取消
            </button>
            <button
              type="submit"
              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"
            >
              创建
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}
