// frontend-react/src/components/TopBar/TopBar.jsx
import React, { useState, useRef, useEffect } from 'react';
import useAppLayoutStore from '../../Store/AppLayoutSlice'; // ✅ 新增
import useUserStore from '../../Store/UserSlice'; // ✅ 新增 - 用户角色
import useWorldBookStore from '../../Store/SideBarLeft/WorldBookSlice';
import useApiConfigStore from '../../Store/SideBarLeft/ApiConfigSlice';
import PageModeToggle from './items/PageModeToggle';
import ThemeToggle from './items/ThemeToggle';
import RegexPanel from '../SideBarLeft/tabs/Regex/RegexPanel'; // ✅ 新增：导入正则管理组件
import './TopBar.css';

const Toolbar = () => {
  const [activePanel, setActivePanel] = useState(null);
  const panelRef = useRef(null);
  
  // ✅ 直接从 AppLayoutStore 获取状态和方法
  const {
    sidebarMode,
    colorTheme,
    setSidebarMode,
    setColorTheme,
  } = useAppLayoutStore();
  
  // ✅ 从 UserStore 获取用户角色和方法
  const { currentUserRole, userRoles, updateRoleName, updateRoleDescription, selectUserRole, addUserRole } = useUserStore();
  
  // 从 Store 获取全局世界书
  const { globalWorldBooks } = useWorldBookStore();
  
  // 从 ApiConfigStore 获取核心和辅助 API 配置
  const { activeMap, fetchProfile } = useApiConfigStore();
  const [coreModel, setCoreModel] = useState('未设置');
  const [assistModel, setAssistModel] = useState('未设置');
  
  // 系统设置状态
  const [settings, setSettings] = useState({
    thinkingTagPrefix: '<thinking>',
    thinkingTagSuffix: '</thinking>',
    currentPresetName: null
  });
  const [settingsLoading, setSettingsLoading] = useState(false);
  const [settingsMessage, setSettingsMessage] = useState({ type: '', text: '' });
  const [settingsActiveTab, setSettingsActiveTab] = useState('display'); // 默认显示分页

  // 点击外部关闭面板 - 使用 useCallback 优化
  const handleClickOutside = React.useCallback((event) => {
    if (panelRef.current && !panelRef.current.contains(event.target)) {
      setActivePanel(null);
    }
  }, []);

  React.useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [handleClickOutside]);
  
  // 加载系统设置
  useEffect(() => {
    if (activePanel === 'settings') {
      loadSettings();
    }
  }, [activePanel]);
  
  const loadSettings = async () => {
    try {
      setSettingsLoading(true);
      const response = await fetch('/api/regex/settings');
      const data = await response.json();
      
      if (data.success) {
        setSettings(data.settings);
      }
    } catch (error) {
      console.error('加载系统设置失败:', error);
      showSettingsMessage('error', '加载设置失败');
    } finally {
      setSettingsLoading(false);
    }
  };
  
  const saveSettings = async () => {
    try {
      setSettingsLoading(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) {
        showSettingsMessage('success', '设置已保存');
      } else {
        showSettingsMessage('error', '保存失败');
      }
    } catch (error) {
      console.error('保存设置失败:', error);
      showSettingsMessage('error', '保存失败');
    } finally {
      setSettingsLoading(false);
    }
  };
  
  const showSettingsMessage = (type, text) => {
    setSettingsMessage({ type, text });
    setTimeout(() => setSettingsMessage({ type: '', text: '' }), 3000);
  };
  
  const handleSettingsInputChange = (field, value) => {
    setSettings(prev => ({
      ...prev,
      [field]: value
    }));
  };

  // ✅ 简化：直接调用 store 方法
  const handleSidebarModeChange = (mode) => {
    setSidebarMode(mode);
  };

  // 处理面板切换
  const handlePanelToggle = (panelName) => {
    if (activePanel === panelName) {
      setActivePanel(null);
    } else {
      setActivePanel(panelName);
    }
  };

  // 关闭面板
  const handleClosePanel = () => {
    setActivePanel(null);
  };

  // 截断文本
  const truncateText = (text, maxLength = 20) => {
    if (!text) return '未选择';
    return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
  };

  return (
    <>
      <div className="top-bar">
        <div className="top-bar-content">
          {/* 左侧：状态徽章区域 */}
          <div className="status-section">
            {/* 当前玩家角色 */}
            <div 
              className="status-badge" 
              title="当前玩家角色"
              onClick={() => handlePanelToggle('currentRole')}
            >
              <span className="status-icon">😊</span>
              <span className="status-label">{truncateText(currentUserRole.name || '未设置', 15)}</span>
            </div>
            
            {/* 核心配置 */}
            <div className="status-badge" title={`核心配置: ${coreModel}`}>
              <span className="status-icon">🔌</span>
              <span className="status-label">{truncateText(coreModel, 12)}</span>
            </div>
            
            {/* 辅助配置 */}
            <div className="status-badge" title={`辅助配置: ${assistModel}`}>
              <span className="status-icon">🔗</span>
              <span className="status-label">{truncateText(assistModel, 12)}</span>
            </div>
            
            {/* 当前预设 */}
            <div className="status-badge" title="当前预设名">
              <span className="status-icon">⚙️</span>
              <span className="status-label">默认预设</span>
            </div>
            
            {/* 激活的世界书 */}
            <div className="status-badge world-info-badge" title="已激活全局世界书" onClick={() => handlePanelToggle('worldBook')}>
              <span className="status-icon">📚</span>
              <span className="status-label">
                {globalWorldBooks.length > 0 
                  ? globalWorldBooks.map(wb => wb.name).join(', ')
                  : '无'}
              </span>
            </div>
          </div>
          
          {/* 右侧：操作按钮区域 */}
          <div className="actions-section">
            {/* 设置按钮 */}
            <button 
              className="action-btn" 
              title="设置"
              onClick={() => handlePanelToggle('settings')}
            >
              ⚙
            </button>
            
            {/* 扩展按钮 */}
            <button 
              className="action-btn" 
              title="扩展"
              onClick={() => handlePanelToggle('extensions')}
            >
              ⊞
            </button>
            
            {/* 页面模式 */}
            <PageModeToggle />

            {/* 主题切换 */}
            <ThemeToggle />
          </div>
        </div>
      </div>

      {/* ✅ 用户角色设置面板 */}
      {activePanel === 'currentRole' && (
        <div className="panel-overlay" ref={panelRef}>
          <div className="panel-content">
            <div className="panel-header">
              <h3>👤 用户角色</h3>
              <button className="close-panel-button" onClick={handleClosePanel} title="关闭">
                ✕
              </button>
            </div>
            <div className="panel-body">
              <div className="settings-section">
                <h4>选择角色</h4>
                <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                  {userRoles.map((role) => (
                    <div
                      key={role.id}
                      onClick={() => selectUserRole(role.id)}
                      style={{
                        padding: '12px',
                        borderRadius: '6px',
                        border: currentUserRole.name === role.name ? '2px solid var(--color-primary)' : '1px solid var(--border-color)',
                        background: currentUserRole.name === role.name ? 'rgba(var(--color-primary-rgb), 0.1)' : 'var(--color-bg-secondary)',
                        cursor: 'pointer',
                        transition: 'all 0.2s'
                      }}
                    >
                      <div style={{ fontWeight: '600', marginBottom: '4px', color: 'var(--color-text-primary)' }}>
                        {role.name}
                      </div>
                      <div style={{ fontSize: '13px', color: 'var(--color-text-secondary)' }}>
                        {role.description || '无描述'}
                      </div>
                    </div>
                  ))}
                </div>
                
                <div className="setting-section" style={{ marginTop: '20px', paddingTop: '20px', borderTop: '1px solid var(--border-color)' }}>
                  <h4>💡 说明</h4>
                  <ul style={{ margin: 0, paddingLeft: '20px', color: 'var(--color-text-secondary)', fontSize: '13px', lineHeight: '1.6' }}>
                    <li>点击角色即可切换当前使用的用户角色</li>
                    <li>角色描述会自动用于预设的 <code>personaDescription</code> 组件</li>
                    <li>设置会自动保存到浏览器本地存储</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 全局世界书面板 - 使用条件渲染优化 */}
      {activePanel === 'worldBook' && (
        <div className="panel-overlay" ref={panelRef}>
          <div className="panel-content">
            <div className="panel-header">
              <h3>全局世界书 ({globalWorldBooks.length})</h3>
              <button className="close-panel-button" onClick={handleClosePanel} title="关闭">
                ✕
              </button>
            </div>
            <div className="panel-body">
              {globalWorldBooks.length > 0 ? (
                <div className="global-books-list-topbar">
                  {globalWorldBooks.map(book => (
                    <div key={book.name} className="global-book-item-topbar">
                      <span className="global-book-name-topbar">{book.name}</span>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="no-global-books-topbar">暂无全局世界书</p>
              )}
            </div>
          </div>
        </div>
      )}

      {/* 设置面板 - 使用条件渲染优化 */}
      {activePanel === 'settings' && (
        <div className="panel-overlay" ref={panelRef}>
          <div className="panel-content settings-panel">
            <div className="panel-header">
              <h2>系统设置</h2>
              <button className="close-panel-button" onClick={handleClosePanel} title="关闭">
                ✕
              </button>
            </div>
            
            {/* 消息提示 */}
            {settingsMessage.text && (
              <div className={`message ${settingsMessage.type}`} style={{ margin: '10px', padding: '8px', borderRadius: '4px' }}>
                {settingsMessage.text}
              </div>
            )}
            
            {/* 分页标签 */}
            <div className="settings-tabs">
              <button
                className={`tab-button ${settingsActiveTab === 'display' ? 'active' : ''}`}
                onClick={() => setSettingsActiveTab('display')}
              >
                显示
              </button>
              <button
                className={`tab-button ${settingsActiveTab === 'formatting' ? 'active' : ''}`}
                onClick={() => setSettingsActiveTab('formatting')}
              >
                格式化
              </button>
              <button
                className={`tab-button ${settingsActiveTab === 'user' ? 'active' : ''}`}
                onClick={() => setSettingsActiveTab('user')}
              >
                用户
              </button>
            </div>
            
            <div className="panel-body" style={{ padding: '16px' }}>
              {settingsLoading && <div className="loading">加载中...</div>}
              
              {/* 显示设置 */}
              {settingsActiveTab === 'display' && (
                <div className="settings-section">
                  <div className="setting-section">
                    <h4>左侧栏模式</h4>
                    <div className="setting-options">
                      <label className={`setting-option ${sidebarMode === 'fixed' ? 'active' : ''}`}>
                        <input 
                          type="radio" 
                          name="sidebarMode" 
                          value="fixed"
                          checked={sidebarMode === 'fixed'}
                          onChange={(e) => handleSidebarModeChange(e.target.value)}
                        />
                        <span>固定</span>
                      </label>
                      <label className={`setting-option ${sidebarMode === 'smart' ? 'active' : ''}`}>
                        <input 
                          type="radio" 
                          name="sidebarMode" 
                          value="smart"
                          checked={sidebarMode === 'smart'}
                          onChange={(e) => handleSidebarModeChange(e.target.value)}
                        />
                        <span>智能</span>
                      </label>
                      <label className={`setting-option ${sidebarMode === 'expanded' ? 'active' : ''}`}>
                        <input 
                          type="radio" 
                          name="sidebarMode" 
                          value="expanded"
                          checked={sidebarMode === 'expanded'}
                          onChange={(e) => handleSidebarModeChange(e.target.value)}
                        />
                        <span>扩展</span>
                      </label>
                    </div>
                    <p className="setting-description">
                      {sidebarMode === 'fixed' && '左侧栏保持默认宽度，不响应交互'}
                      {sidebarMode === 'smart' && '鼠标悬停时自动展开，移开后收起'}
                      {sidebarMode === 'expanded' && '左侧栏保持最大宽度'}
                    </p>
                  </div>
                </div>
              )}
              
              {/* 格式化设置 */}
              {settingsActiveTab === 'formatting' && (
                <div className="settings-section">
                  <div className="setting-section">
                    <h4>思考标签配置</h4>
                    <div style={{ marginBottom: '16px' }}>
                      <label style={{ display: 'block', marginBottom: '8px', fontSize: '14px', fontWeight: '500', color: 'var(--color-text-primary)' }}>前缀</label>
                      <input
                        type="text"
                        value={settings.thinkingTagPrefix}
                        onChange={(e) => handleSettingsInputChange('thinkingTagPrefix', e.target.value)}
                        placeholder="<thinking>"
                        className="settings-input"
                      />
                    </div>
                    
                    <div style={{ marginBottom: '16px' }}>
                      <label style={{ display: 'block', marginBottom: '8px', fontSize: '14px', fontWeight: '500', color: 'var(--color-text-primary)' }}>后缀</label>
                      <input
                        type="text"
                        value={settings.thinkingTagSuffix}
                        onChange={(e) => handleSettingsInputChange('thinkingTagSuffix', e.target.value)}
                        placeholder="</thinking>"
                        className="settings-input"
                      />
                    </div>
                    
                    <div className="preview-box">
                      <div className="original" style={{ marginBottom: '12px' }}>
                        <strong style={{ display: 'block', marginBottom: '4px', fontSize: '12px', color: 'var(--color-text-secondary)' }}>原始内容：</strong>
                        <p style={{ margin: 0, padding: '8px', background: 'rgba(0, 0, 0, 0.2)', borderRadius: '3px', fontFamily: 'Courier New, monospace', fontSize: '12px', color: 'var(--color-text-primary)' }}>
                          这是回复 {settings.thinkingTagPrefix}思考过程{settings.thinkingTagSuffix} 继续
                        </p>
                      </div>
                      <div className="processed">
                        <strong style={{ display: 'block', marginBottom: '4px', fontSize: '12px', color: 'var(--color-text-secondary)' }}>处理后：</strong>
                        <p style={{ margin: 0, padding: '8px', background: 'rgba(0, 0, 0, 0.2)', borderRadius: '3px', fontFamily: 'Courier New, monospace', fontSize: '12px', color: 'var(--color-text-primary)' }}>
                          这是回复  继续
                        </p>
                      </div>
                    </div>
                  </div>
                  
                  <div className="setting-section" style={{ marginTop: '20px', paddingTop: '20px', borderTop: '1px solid var(--border-color)' }}>
                    <h4>📝 正则管理</h4>
                    <p className="settings-hint" style={{ marginBottom: '16px' }}>
                      管理全局和预设的正则规则。
                    </p>
                    
                    {/* ✅ 使用 RegexPanel 组件 */}
                    <RegexPanel />
                  </div>
                  
                  <div style={{ marginTop: '20px' }}>
                    <button 
                      className="btn-primary" 
                      onClick={saveSettings} 
                      disabled={settingsLoading}
                    >
                      {settingsLoading ? '保存中...' : '保存设置'}
                    </button>
                  </div>
                </div>
              )}
              
              {/* 用户设置 */}
              {settingsActiveTab === 'user' && (
                <div className="settings-section">
                  <div className="setting-section">
                    <h4>当前预设</h4>
                    <input
                      type="text"
                      value={settings.currentPresetName || ''}
                      onChange={(e) => handleSettingsInputChange('currentPresetName', e.target.value || null)}
                      placeholder="未选择"
                      className="settings-input"
                    />
                    <small className="settings-hint">
                      影响全局正则规则的启用
                    </small>
                  </div>
                  
                  <div style={{ marginTop: '20px' }}>
                    <button 
                      className="btn-primary" 
                      onClick={saveSettings} 
                      disabled={settingsLoading}
                    >
                      {settingsLoading ? '保存中...' : '保存设置'}
                    </button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* 拓展面板 - 使用条件渲染优化 */}
      {activePanel === 'extensions' && (
        <div className="panel-overlay" ref={panelRef}>
          <div className="panel-content">
            <div className="panel-header">
              <h3>功能拓展</h3>
              <button className="close-panel-button" onClick={handleClosePanel} title="关闭">
                ✕
              </button>
            </div>
            <div className="panel-body">
              <p>功能拓展内容...</p>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default Toolbar;
