import React, { useState, useEffect } from 'react';
import usePresetStore from '../../../../Store/SideBarLeft/PresetSlice';
import './RegexPanel.css';

const RegexPanel = () => {
  // 状态管理
  const [globalRulesets, setGlobalRulesets] = useState([]);
  const [presetRulesets, setPresetRulesets] = useState([]);
  const [editingRule, setEditingRule] = useState(null);
  const [showEditor, setShowEditor] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  
  // 折叠状态
  const [collapsedSections, setCollapsedSections] = useState({
    global: false,
    preset: false
  });

  // 获取当前预设
  const { selectedPreset } = usePresetStore();

  // 编辑器表单状态
  const [formData, setFormData] = useState({
    id: '',
    scriptName: '',
    findRegex: '',
    replaceString: '',
    trimStrings: [],
    placement: [2], // 默认 AI输出 (SillyTavern 标准：0=System, 1=User Input, 2=AI Output)
    disabled: false,
    markdownOnly: false,
    promptOnly: false,
    runOnEdit: true,
    substituteRegex: 0,
    minDepth: null,
    maxDepth: null
  });

  // 作用范围选项（SillyTavern 官方标准）
  const placementOptions = [
    { value: 0, label: '系统提示词' },    // System Prompt
    { value: 1, label: '用户输入' },      // User Input
    { value: 2, label: 'AI输出' },        // AI Output
    { value: 3, label: '快捷命令' },      // Quick Reply
    { value: 4, label: '世界信息' },      // World Info
    { value: 5, label: '推理' }           // Reasoning/Thinking
  ];

  // 替换模式选项
  const substituteOptions = [
    { value: 0, label: '不替换' },
    { value: 1, label: '替换首次匹配' },
    { value: 2, label: '替换所有匹配' }
  ];

  // 加载全局规则集
  useEffect(() => {
    fetchGlobalRulesets();
  }, []);

  // 当预设变化时加载预设规则集
  useEffect(() => {
    if (selectedPreset) {
      fetchPresetRulesets(selectedPreset);
    } else {
      setPresetRulesets([]);
    }
  }, [selectedPreset]);

  const fetchGlobalRulesets = async () => {
    try {
      setIsLoading(true);
      const response = await fetch('/api/regex/rulesets/global');
      const data = await response.json();
      
      if (data.success) {
        setGlobalRulesets(data.rulesets || []);
      }
    } catch (error) {
      console.error('加载全局规则集失败:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const fetchPresetRulesets = async (presetName) => {
    try {
      const response = await fetch(`/api/regex/rulesets/preset/${encodeURIComponent(presetName)}`);
      const data = await response.json();
      
      if (data.success && data.ruleset) {
        setPresetRulesets([data.ruleset]);
      } else {
        setPresetRulesets([]);
      }
    } catch (error) {
      console.error('加载预设规则集失败:', error);
      setPresetRulesets([]);
    }
  };

  // 切换折叠状态
  const toggleCollapse = (section) => {
    setCollapsedSections(prev => ({
      ...prev,
      [section]: !prev[section]
    }));
  };

  // 打开编辑器 - 新建规则
  const handleNewRule = (scope = 'global') => {
    setFormData({
      id: crypto.randomUUID(),
      scriptName: '',
      findRegex: '',
      replaceString: '',
      trimStrings: [],
      placement: [2],  // 默认 AI Output
      disabled: false,
      markdownOnly: false,
      promptOnly: false,
      runOnEdit: true,
      substituteRegex: 0,
      minDepth: null,
      maxDepth: null
    });
    setEditingRule({ scope });
    setShowEditor(true);
  };

  // 打开编辑器 - 编辑规则
  const handleEditRule = (rule) => {
    setFormData({
      ...rule,
      placement: rule.placement || [2],
      trimStrings: rule.trimStrings || []
    });
    setEditingRule(rule);
    setShowEditor(true);
  };

  // 保存规则
  const handleSaveRule = async () => {
    try {
      setIsLoading(true);
      
      const scope = editingRule?.scope || 'global';
      const presetName = scope === 'preset' ? selectedPreset : null;
      
      const response = await fetch('/api/regex/rules', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          rule: formData,
          scope: scope,
          name: presetName
        })
      });

      const data = await response.json();
      
      if (data.success) {
        setShowEditor(false);
        if (scope === 'preset') {
          fetchPresetRulesets(selectedPreset);
        } else {
          fetchGlobalRulesets();
        }
      } else {
        alert('保存失败: ' + data.message);
      }
    } catch (error) {
      console.error('保存规则失败:', error);
      alert('保存失败: ' + error.message);
    } finally {
      setIsLoading(false);
    }
  };

  // 删除规则
  const handleDeleteRule = async (ruleId, ruleName, sectionKey = 'global') => {
    if (!confirm(`确定要删除规则 "${ruleName}" 吗？`)) {
      return;
    }

    try {
      setIsLoading(true);
      
      const scope = sectionKey === 'preset' ? 'preset' : 'global';
      const presetName = scope === 'preset' ? selectedPreset : null;
      
      const url = new URL(`/api/regex/rules/${ruleId}`, window.location.origin);
      url.searchParams.set('scope', scope);
      if (presetName) {
        url.searchParams.set('name', presetName);
      }
      
      const response = await fetch(url.toString(), {
        method: 'DELETE'
      });

      const data = await response.json();
      
      if (data.success) {
        alert('规则已删除');
        if (sectionKey === 'preset') {
          fetchPresetRulesets(selectedPreset);
        } else {
          fetchGlobalRulesets();
        }
      } else {
        alert('删除失败: ' + data.message);
      }
    } catch (error) {
      console.error('删除规则失败:', error);
      alert('删除失败: ' + error.message);
    } finally {
      setIsLoading(false);
    }
  };

  // 切换规则启用状态
  const handleToggleRule = async (rule, sectionKey = 'global') => {
    try {
      const updatedRule = { ...rule, disabled: !rule.disabled };
      const scope = sectionKey === 'preset' ? 'preset' : 'global';
      const presetName = scope === 'preset' ? selectedPreset : null;
      
      const response = await fetch('/api/regex/rules', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          rule: updatedRule,
          scope: scope,
          name: presetName
        })
      });

      const data = await response.json();
      
      if (data.success) {
        if (sectionKey === 'preset') {
          fetchPresetRulesets(selectedPreset);
        } else {
          fetchGlobalRulesets();
        }
      }
    } catch (error) {
      console.error('更新规则状态失败:', error);
    }
  };

  // 更新表单字段
  const updateFormField = (field, value) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };

  // 切换作用范围
  const togglePlacement = (value) => {
    setFormData(prev => {
      const current = prev.placement || [];
      const updated = current.includes(value)
        ? current.filter(v => v !== value)
        : [...current, value];
      return { ...prev, placement: updated };
    });
  };

  // 更新修剪字符串
  const updateTrimStrings = (value) => {
    const trimStrings = value.split('\n').filter(s => s.trim());
    setFormData(prev => ({ ...prev, trimStrings }));
  };

  // 渲染编辑器
  const renderEditor = () => {
    if (!showEditor) return null;

    return (
      <div className="regex-editor-overlay">
        <div className="regex-editor-modal">
          <div className="regex-editor-header">
            <h3>正则表达式编辑器</h3>
            <button className="close-btn" onClick={() => setShowEditor(false)}>×</button>
          </div>

          <div className="regex-editor-body">
            {/* 脚本名称 */}
            <div className="form-group">
              <label>脚本名称</label>
              <input
                type="text"
                value={formData.scriptName}
                onChange={(e) => updateFormField('scriptName', e.target.value)}
                placeholder="例如：隐藏thinking"
              />
            </div>

            {/* 查找正则表达式 */}
            <div className="form-group">
              <label>查找正则表达式</label>
              <input
                type="text"
                value={formData.findRegex}
                onChange={(e) => updateFormField('findRegex', e.target.value)}
                placeholder="/pattern/flags"
              />
              <small>SillyTavern 格式，例如：/&lt;thinking&gt;[\\s\\S]*?&lt;\\/thinking&gt;/gs</small>
            </div>

            {/* 替换为 */}
            <div className="form-group">
              <label>替换为</label>
              <textarea
                value={formData.replaceString}
                onChange={(e) => updateFormField('replaceString', e.target.value)}
                placeholder="使用 {{match}} 或 $1, $2 等捕获组"
                rows={3}
              />
            </div>

            {/* 修剪掉 */}
            <div className="form-group">
              <label>修剪掉</label>
              <textarea
                value={formData.trimStrings.join('\n')}
                onChange={(e) => updateTrimStrings(e.target.value)}
                placeholder="每行一个字符串"
                rows={2}
              />
            </div>

            {/* 作用范围和其他选项 - 紧凑布局 */}
            <div className="form-row compact-options">
              <div className="form-section">
                <h4>作用范围</h4>
                <div className="checkbox-group compact">
                  {placementOptions.map(opt => (
                    <label key={opt.value} className="checkbox-item">
                      <input
                        type="checkbox"
                        checked={formData.placement.includes(opt.value)}
                        onChange={() => togglePlacement(opt.value)}
                      />
                      <span>{opt.label}</span>
                    </label>
                  ))}
                </div>
              </div>

              <div className="form-section">
                <h4>其他选项</h4>
                <div className="checkbox-group compact">
                  <label className="checkbox-item" title="禁用此规则，使其不生效">
                    <input
                      type="checkbox"
                      checked={formData.disabled}
                      onChange={(e) => updateFormField('disabled', e.target.checked)}
                    />
                    <span>已禁用</span>
                  </label>
                  <label className="checkbox-item" title="用户编辑消息时也重新应用此规则">
                    <input
                      type="checkbox"
                      checked={formData.runOnEdit}
                      onChange={(e) => updateFormField('runOnEdit', e.target.checked)}
                    />
                    <span>编辑时运行</span>
                  </label>
                  <label className="checkbox-item" title="勾选后：只在前端显示时应用正则，不修改存储的原始数据">
                    <input
                      type="checkbox"
                      checked={formData.markdownOnly}
                      onChange={(e) => updateFormField('markdownOnly', e.target.checked)}
                    />
                    <span>仅影响显示</span>
                  </label>
                  <label className="checkbox-item" title="勾选后：只在发送给LLM时应用正则，不修改存储的原始数据">
                    <input
                      type="checkbox"
                      checked={formData.promptOnly}
                      onChange={(e) => updateFormField('promptOnly', e.target.checked)}
                    />
                    <span>仅影响提示词</span>
                  </label>
                </div>
              </div>
            </div>

            {/* 深度设置 */}
            <div className="form-row">
              <div className="form-group small">
                <label>最小深度</label>
                <input
                  type="number"
                  value={formData.minDepth || ''}
                  onChange={(e) => updateFormField('minDepth', e.target.value ? parseInt(e.target.value) : null)}
                  placeholder="无限"
                />
              </div>
              <div className="form-group small">
                <label>最大深度</label>
                <input
                  type="number"
                  value={formData.maxDepth || ''}
                  onChange={(e) => updateFormField('maxDepth', e.target.value ? parseInt(e.target.value) : null)}
                  placeholder="无限"
                />
              </div>
            </div>

            {/* 替换模式 */}
            <div className="form-group">
              <label>替换模式</label>
              <select
                value={formData.substituteRegex}
                onChange={(e) => updateFormField('substituteRegex', parseInt(e.target.value))}
              >
                {substituteOptions.map(opt => (
                  <option key={opt.value} value={opt.value}>{opt.label}</option>
                ))}
              </select>
            </div>
          </div>

          <div className="regex-editor-footer">
            <button className="btn-cancel" onClick={() => setShowEditor(false)}>
              取消
            </button>
            <button className="btn-save" onClick={handleSaveRule} disabled={isLoading}>
              {isLoading ? '保存中...' : '保存'}
            </button>
          </div>
        </div>
      </div>
    );
  };

  // 渲染可折叠的规则列表
  const renderCollapsibleRules = (title, rulesets, sectionKey, icon = '📜') => {
    const allRules = rulesets.flatMap(ruleset => ruleset.rules || []);
    const isCollapsed = collapsedSections[sectionKey];

    return (
      <div className="regex-section">
        <div 
          className="regex-section-header"
          onClick={() => toggleCollapse(sectionKey)}
        >
          <div className="section-title">
            <span className="collapse-icon">{isCollapsed ? '▶' : '▼'}</span>
            <span className="section-icon">{icon}</span>
            <h4>{title}</h4>
            <span className="rule-count">({allRules.length})</span>
          </div>
          {!isCollapsed && allRules.length > 0 && (
            <button className="btn-add-rule-small" onClick={(e) => {
              e.stopPropagation();
              handleNewRule(sectionKey);
            }}>
              + 添加
            </button>
          )}
        </div>
        
        {!isCollapsed && (
          <div className="regex-section-content">
            {allRules.length === 0 ? (
              <div className="empty-rules">
                <p>暂无规则</p>
              </div>
            ) : (
              <div className="rules-list">
                {allRules.map((rule) => (
                  <div key={rule.id} className="rule-item">
                    <div className="rule-info">
                      <span className="rule-name">{rule.scriptName}</span>
                      <div className="rule-badges">
                        {rule.disabled && <span className="rule-badge disabled" title="此规则已禁用">已禁用</span>}
                        {rule.promptOnly && <span className="rule-badge prompt" title="不影响显示给用户的内容">不影响显示</span>}
                        {rule.markdownOnly && <span className="rule-badge markdown" title="不影响发送给 AI 的内容">不影响发送</span>}
                      </div>
                    </div>
                    <div className="rule-actions">
                      <label className="toggle-switch" onClick={(e) => e.stopPropagation()}>
                        <input
                          type="checkbox"
                          checked={!rule.disabled}
                          onChange={() => handleToggleRule(rule, sectionKey)}
                        />
                        <span className="toggle-slider"></span>
                      </label>
                      <button className="icon-btn" onClick={(e) => {
                        e.stopPropagation();
                        handleEditRule(rule);
                      }} title="编辑">
                        ✏️
                      </button>
                      <button className="icon-btn" onClick={(e) => {
                        e.stopPropagation();
                        handleDeleteRule(rule.id, rule.scriptName, sectionKey);
                      }} title="删除">
                        🗑️
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}
      </div>
    );
  };

  return (
    <div className="regex-panel">
      <div className="regex-panel-header">
        <h2>正则管理</h2>
        <p className="subtitle">管理全局和预设的正则规则。</p>
      </div>

      {/* 左右布局 */}
      <div className="regex-layout">
        {/* 左侧：规则列表 */}
        <div className="regex-left">
          {/* 全局规则 */}
          {renderCollapsibleRules('全局正则脚本', globalRulesets, 'global', '🌍')}
          
          {/* 预设规则 */}
          {renderCollapsibleRules(
            selectedPreset ? `预设正则脚本 (${selectedPreset})` : '预设正则脚本', 
            presetRulesets, 
            'preset', 
            '⚙️'
          )}
        </div>

        {/* 右侧：说明和快速操作 */}
        <div className="regex-right">
          <div className="regex-info-card">
            <h4>📖 正则规则说明</h4>
            <ul>
              <li><strong>全局规则：</strong>影响所有角色和聊天</li>
              <li><strong>预设规则：</strong>仅影响当前预设</li>
              <li><strong>仅提示词：</strong>只应用于发送LLM的内容</li>
              <li><strong>仅格式：</strong>只应用于Markdown渲染</li>
            </ul>
            
            <h4 style={{ marginTop: '20px' }}>⚡ 快捷操作</h4>
            <div className="quick-actions">
              <button className="btn-quick" onClick={() => handleNewRule('global')}>
                + 新建全局规则
              </button>
              {selectedPreset && (
                <button className="btn-quick" onClick={() => handleNewRule('preset')}>
                  + 新建预设规则
                </button>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* 编辑器弹窗 */}
      {renderEditor()}
    </div>
  );
};

export default RegexPanel;
