import React, { useState } from 'react';
import './TavernHelper.css';

/**
 * 酒馆助手组件（Tavern Helper）
 * 
 * 模仿 SillyTavern 的酒馆助手插件，提供：
 * - 渲染标签页：控制代码块渲染
 * - 脚本标签页：管理 JavaScript 脚本
 * - 工具标签页：实用工具
 * - 优化标签页：性能优化选项
 * - 开发标签页：开发者工具
 */
const TavernHelper = () => {
  const [activeTab, setActiveTab] = useState('render');
  
  // 渲染设置
  const [renderSettings, setRenderSettings] = useState({
    enabled: true,
    renderDepth: 0,
    codeFoldEnabled: true,
    codeFoldMode: 'frontend-only', // all, frontend-only, disabled
    blobUrlRender: false,
    disableCodeHighlight: true,
    streamRender: true,
  });
  
  // 脚本状态
  const [globalScriptsEnabled, setGlobalScriptsEnabled] = useState(false);
  const [characterScriptsEnabled, setCharacterScriptsEnabled] = useState(false);
  const [presetScriptsEnabled, setPresetScriptsEnabled] = useState(true);
  
  const tabs = [
    { id: 'render', label: '渲染', icon: '✎' },
    { id: 'scripts', label: '脚本', icon: '' },
    { id: 'tools', label: '工具', icon: '' },
    { id: 'optimization', label: '优化', icon: '⚡' },
    { id: 'dev', label: '开发', icon: '' },
  ];
  
  return (
    <div className="tavern-helper">
      <div className="tavern-helper-header">
        <h3>酒馆助手 <span className="badge-new">New!</span></h3>
        <span className="version">Ver 4.8.4</span>
        <button className="btn-extension-info">扩展信息</button>
      </div>
      
      {/* 标签页导航 */}
      <div className="tavern-helper-tabs">
        {tabs.map(tab => (
          <button
            key={tab.id}
            className={`tab-button ${activeTab === tab.id ? 'active' : ''}`}
            onClick={() => setActiveTab(tab.id)}
          >
            <span className="tab-icon">{tab.icon}</span>
            <span className="tab-label">{tab.label}</span>
          </button>
        ))}
      </div>
      
      {/* 标签页内容 */}
      <div className="tavern-helper-content">
        {activeTab === 'render' && <RenderTab settings={renderSettings} onChange={setRenderSettings} />}
        {activeTab === 'scripts' && (
          <ScriptsTab
            globalEnabled={globalScriptsEnabled}
            characterEnabled={characterScriptsEnabled}
            presetEnabled={presetScriptsEnabled}
            onGlobalToggle={setGlobalScriptsEnabled}
            onCharacterToggle={setCharacterScriptsEnabled}
            onPresetToggle={setPresetScriptsEnabled}
          />
        )}
        {activeTab === 'tools' && <ToolsTab />}
        {activeTab === 'optimization' && <OptimizationTab />}
        {activeTab === 'dev' && <DevTab />}
      </div>
    </div>
  );
};

/**
 * 渲染标签页
 */
const RenderTab = ({ settings, onChange }) => {
  return (
    <div className="tab-content render-tab">
      {/* 启用渲染器 */}
      <div className="setting-group">
        <div className="setting-header">
          <label className="toggle-label">
            <input
              type="checkbox"
              checked={settings.enabled}
              onChange={(e) => onChange({ ...settings, enabled: e.target.checked })}
            />
            <span className="toggle-slider"></span>
          </label>
          <div className="setting-info">
            <h4>启用渲染器</h4>
            <p className="setting-desc">启用后，符合条件的代码块将被渲染</p>
          </div>
        </div>
      </div>
      
      {/* 渲染优化 */}
      <div className="setting-section">
        <h5 className="section-title">⚡ 渲染优化</h5>
        
        <div className="setting-item">
          <label>渲染深度</label>
          <div className="setting-control">
            <input
              type="number"
              value={settings.renderDepth}
              onChange={(e) => onChange({ ...settings, renderDepth: parseInt(e.target.value) })}
              min="0"
            />
            <p className="field-hint">设置需要渲染的楼层数，从最新楼层开始计数。为 0 时，将渲染所有楼层</p>
          </div>
        </div>
        
        <div className="setting-item">
          <label>启用代码折叠</label>
          <div className="setting-control">
            <div className="radio-group">
              <button
                className={`radio-btn ${settings.codeFoldMode === 'all' ? 'active' : ''}`}
                onClick={() => onChange({ ...settings, codeFoldMode: 'all' })}
              >
                全部
              </button>
              <button
                className={`radio-btn ${settings.codeFoldMode === 'frontend-only' ? 'active' : ''}`}
                onClick={() => onChange({ ...settings, codeFoldMode: 'frontend-only' })}
              >
                仅前端
              </button>
              <button
                className={`radio-btn ${settings.codeFoldMode === 'disabled' ? 'active' : ''}`}
                onClick={() => onChange({ ...settings, codeFoldMode: 'disabled' })}
              >
                禁用
              </button>
            </div>
            <p className="field-hint">折叠指定类型的代码块，当选择"仅前端"时，将只折叠可渲染成前端界面但没被渲染的代码块</p>
          </div>
        </div>
        
        <div className="setting-header">
          <label className="toggle-label">
            <input
              type="checkbox"
              checked={settings.blobUrlRender}
              onChange={(e) => onChange({ ...settings, blobUrlRender: e.target.checked })}
            />
            <span className="toggle-slider"></span>
          </label>
          <div className="setting-info">
            <h4>启用 Blob URL 渲染</h4>
            <p className="setting-desc">使用 Blob URL 渲染前端界面，更方便 f12 开发者工具调试；但某些浏览器可能不支持</p>
          </div>
        </div>
        
        <div className="setting-header">
          <label className="toggle-label">
            <input
              type="checkbox"
              checked={settings.disableCodeHighlight}
              onChange={(e) => onChange({ ...settings, disableCodeHighlight: e.target.checked })}
            />
            <span className="toggle-slider"></span>
          </label>
          <div className="setting-info">
            <h4>取消前端代码高亮</h4>
            <p className="setting-desc">避免酒馆对可渲染成前端界面的代码块进行语法高亮，从而提升渲染性能</p>
          </div>
        </div>
      </div>
      
      {/* 实验功能 */}
      <div className="setting-section experimental">
        <h5 className="section-title"> 实验功能</h5>
        
        <div className="setting-header">
          <label className="toggle-label">
            <input
              type="checkbox"
              checked={settings.streamRender}
              onChange={(e) => onChange({ ...settings, streamRender: e.target.checked })}
            />
            <span className="toggle-slider"></span>
          </label>
          <div className="setting-info">
            <h4>允许流式渲染</h4>
            <p className="setting-desc">在AI流式输出时就渲染，某些前端界面可能无法这样渲染。此外，这可能与某些脚本、插件、酒馆美化不兼容</p>
          </div>
        </div>
      </div>
    </div>
  );
};

/**
 * 脚本标签页
 */
const ScriptsTab = ({
  globalEnabled,
  characterEnabled,
  presetEnabled,
  onGlobalToggle,
  onCharacterToggle,
  onPresetToggle,
}) => {
  const [searchQuery, setSearchQuery] = useState('');
  
  return (
    <div className="tab-content scripts-tab">
      {/* 工具栏 */}
      <div className="scripts-toolbar">
        <button className="btn-tool">➕ 脚本</button>
        <button className="btn-tool">📁 文件夹</button>
        <button className="btn-tool">📥 导入</button>
        <button className="btn-tool">📦 内置库</button>
      </div>
      
      {/* 搜索框 */}
      <div className="search-box">
        <input
          type="text"
          placeholder="搜索（支持普通和/正则/）"
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
        />
        <span className="search-icon"></span>
      </div>
      
      {/* 全局脚本 */}
      <div className="script-section">
        <div className="section-header">
          <h4>全局脚本</h4>
          <label className="toggle-label">
            <input
              type="checkbox"
              checked={globalEnabled}
              onChange={(e) => onGlobalToggle(e.target.checked)}
            />
            <span className="toggle-slider"></span>
          </label>
        </div>
        <p className="section-desc">酒馆全局可用</p>
        
        <div className="script-list">
          <div className="script-item">
            <span className="drag-handle">☰</span>
            <span className="script-name">【骰子系统】-自动更新</span>
            <div className="script-actions">
              <button className="btn-icon" title="启用/禁用"></button>
              <button className="btn-icon" title="信息">ℹ️</button>
              <button className="btn-icon" title="编辑">✏️</button>
              <button className="btn-icon" title="更多">⋯</button>
              <button className="btn-icon danger" title="删除">🗑️</button>
            </div>
          </div>
          <div className="script-item">
            <span className="drag-handle">☰</span>
            <span className="script-name">蚀心入魔·数据库</span>
            <div className="script-actions">
              <button className="btn-icon" title="启用/禁用">🔘</button>
              <button className="btn-icon" title="信息">ℹ️</button>
              <button className="btn-icon" title="编辑">✏️</button>
              <button className="btn-icon" title="更多">⋯</button>
              <button className="btn-icon danger" title="删除">🗑️</button>
            </div>
          </div>
        </div>
      </div>
      
      {/* 角色脚本 */}
      <div className="script-section">
        <div className="section-header">
          <h4>角色脚本</h4>
          <label className="toggle-label">
            <input
              type="checkbox"
              checked={characterEnabled}
              onChange={(e) => onCharacterToggle(e.target.checked)}
            />
            <span className="toggle-slider"></span>
          </label>
        </div>
        <p className="section-desc">绑定到当前角色卡</p>
        
        <div className="empty-state">
          <p>暂无脚本本</p>
        </div>
      </div>
      
      {/* 预设脚本 */}
      <div className="script-section">
        <div className="section-header">
          <h4>预设脚本</h4>
          <label className="toggle-label">
            <input
              type="checkbox"
              checked={presetEnabled}
              onChange={(e) => onPresetToggle(e.target.checked)}
            />
            <span className="toggle-slider"></span>
          </label>
        </div>
        <p className="section-desc">绑定到当前预设</p>
        
        <div className="script-list">
          <div className="script-item">
            <span className="drag-handle">☰</span>
            <span className="script-name">import-mvu</span>
            <div className="script-actions">
              <button className="btn-icon" title="启用/禁用">🔘</button>
              <button className="btn-icon" title="信息">ℹ️</button>
              <button className="btn-icon" title="编辑">✏️</button>
              <button className="btn-icon" title="更多"></button>
              <button className="btn-icon danger" title="删除">🗑️</button>
            </div>
          </div>
          <div className="script-item">
            <span className="drag-handle">☰</span>
            <span className="script-name">月经周期计算器</span>
            <div className="script-actions">
              <button className="btn-icon" title="启用/禁用">🔘</button>
              <button className="btn-icon" title="信息">ℹ️</button>
              <button className="btn-icon" title="编辑">✏️</button>
              <button className="btn-icon" title="更多"></button>
              <button className="btn-icon danger" title="删除">🗑️</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

/**
 * 工具标签页（占位）
 */
const ToolsTab = () => {
  return (
    <div className="tab-content tools-tab">
      <div className="empty-state">
        <h3>🔧 工具</h3>
        <p>实用工具即将推出...</p>
      </div>
    </div>
  );
};

/**
 * 优化标签页（占位）
 */
const OptimizationTab = () => {
  return (
    <div className="tab-content optimization-tab">
      <div className="empty-state">
        <h3> 优化</h3>
        <p>性能优化选项即将推出...</p>
      </div>
    </div>
  );
};

/**
 * 开发标签页（占位）
 */
const DevTab = () => {
  return (
    <div className="tab-content dev-tab">
      <div className="empty-state">
        <h3>🛠 开发</h3>
        <p>开发者工具即将推出...</p>
      </div>
    </div>
  );
};

export default TavernHelper;
