import React, { useState, useEffect } from 'react';
import './Settings.css';
import RegexPanel from '../Regex/RegexPanel';

/**
 * 系统设置组件
 * 
 * 按功能分页展示：
 * - 正则规则设置
 * - 思考标签配置
 * - 其他系统设置
 */
const Settings = () => {
  const [activeTab, setActiveTab] = useState('regex');
  const [settings, setSettings] = useState({
    thinkingTagPrefix: '<thinking>',
    thinkingTagSuffix: '</thinking>',
    currentPresetName: null
  });
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState({ type: '', text: '' });

  // 加载系统设置
  useEffect(() => {
    loadSettings();
  }, []);

  const loadSettings = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/regex/settings');
      const data = await response.json();
      
      if (data.success) {
        setSettings(data.settings);
      }
    } catch (error) {
      console.error('加载系统设置失败:', error);
      showMessage('error', '加载设置失败');
    } finally {
      setLoading(false);
    }
  };

  const saveSettings = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/regex/settings', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(settings)
      });
      
      const data = await response.json();
      
      if (data.success) {
        showMessage('success', '设置已保存');
      } else {
        showMessage('error', '保存失败');
      }
    } catch (error) {
      console.error('保存设置失败:', error);
      showMessage('error', '保存失败');
    } finally {
      setLoading(false);
    }
  };

  const showMessage = (type, text) => {
    setMessage({ type, text });
    setTimeout(() => setMessage({ type: '', text: '' }), 3000);
  };

  const handleInputChange = (field, value) => {
    setSettings(prev => ({
      ...prev,
      [field]: value
    }));
  };

  return (
    <div className="settings-container">
      {/* 消息提示 */}
      {message.text && (
        <div className={`message ${message.type}`}>
          {message.text}
        </div>
      )}

      {/* SillyTavern 风格：左右分栏布局 */}
      <div className="settings-layout">
        {/* 左侧：垂直标签栏 */}
        <div className="settings-sidebar">
          <button
            className={`sidebar-tab ${activeTab === 'regex' ? 'active' : ''}`}
            onClick={() => setActiveTab('regex')}
          >
            <span className="tab-icon">📝</span>
            <span className="tab-label">正则规则</span>
          </button>
          <button
            className={`sidebar-tab ${activeTab === 'thinking' ? 'active' : ''}`}
            onClick={() => setActiveTab('thinking')}
          >
            <span className="tab-icon">💭</span>
            <span className="tab-label">思考标签</span>
          </button>
          <button
            className={`sidebar-tab ${activeTab === 'general' ? 'active' : ''}`}
            onClick={() => setActiveTab('general')}
          >
            <span className="tab-icon">⚙️</span>
            <span className="tab-label">通用设置</span>
          </button>
        </div>

        {/* 右侧：内容区域 */}
        <div className="settings-main">
          {loading && <div className="loading">加载中...</div>}

          {/* 正则规则设置 */}
          {activeTab === 'regex' && (
            <div className="settings-panel">
              <RegexPanel />
            </div>
          )}

          {/* 思考标签配置 */}
          {activeTab === 'thinking' && (
            <div className="settings-panel">
              <div className="panel-header">
                <h3>💭 思考标签配置</h3>
                <p className="panel-description">
                  配置 AI 推理/思考内容的标记标签
                </p>
              </div>
              
              <div className="settings-group">
                <div className="group-title">标签设置</div>
                <div className="setting-row">
                  <div className="row-label">前缀</div>
                  <div className="row-content">
                    <input
                      type="text"
                      value={settings.thinkingTagPrefix}
                      onChange={(e) => handleInputChange('thinkingTagPrefix', e.target.value)}
                      placeholder="&lt;thinking&gt;"
                      className="text-input"
                    />
                    <small className="hint-text">默认值：&lt;thinking&gt;</small>
                  </div>
                </div>

                <div className="setting-row">
                  <div className="row-label">后缀</div>
                  <div className="row-content">
                    <input
                      type="text"
                      value={settings.thinkingTagSuffix}
                      onChange={(e) => handleInputChange('thinkingTagSuffix', e.target.value)}
                      placeholder="&lt;/thinking&gt;"
                      className="text-input"
                    />
                    <small className="hint-text">默认值：&lt;/thinking&gt;</small>
                  </div>
                </div>
              </div>

              <div className="settings-group">
                <div className="group-title">效果预览</div>
                <div className="preview-container">
                  <div className="preview-section">
                    <div className="preview-label">原始内容：</div>
                    <div className="preview-code">
                      这是回复 {settings.thinkingTagPrefix}思考过程{settings.thinkingTagSuffix} 继续
                    </div>
                  </div>
                  <div className="preview-section">
                    <div className="preview-label">处理后：</div>
                    <div className="preview-code processed">
                      这是回复  继续
                    </div>
                  </div>
                </div>
              </div>

              <div className="settings-group actions-group">
                <button className="btn-save" onClick={saveSettings} disabled={loading}>
                  {loading ? '保存中...' : '💾 保存设置'}
                </button>
              </div>
            </div>
          )}

          {/* 通用设置 */}
          {activeTab === 'general' && (
            <div className="settings-panel">
              <div className="panel-header">
                <h3>⚙️ 通用设置</h3>
                <p className="panel-description">
                  其他系统级配置
                </p>
              </div>
              
              <div className="settings-group">
                <div className="group-title">预设配置</div>
                <div className="setting-row">
                  <div className="row-label">当前预设</div>
                  <div className="row-content">
                    <input
                      type="text"
                      value={settings.currentPresetName || ''}
                      onChange={(e) => handleInputChange('currentPresetName', e.target.value || null)}
                      placeholder="未选择"
                      className="text-input"
                    />
                    <small className="hint-text">影响全局正则规则的启用</small>
                  </div>
                </div>
              </div>

              <div className="settings-group actions-group">
                <button className="btn-save" onClick={saveSettings} disabled={loading}>
                  {loading ? '保存中...' : '💾 保存设置'}
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default Settings;
