import React, { useState, useEffect } from 'react';
import './Settings.css';
import useChatBoxStore from '../../../Store/Mid/ChatBoxSlice';
import { HistoryMode } from '../../../types/internal.types';

/**
 * 设置Tab - 显示和编辑当前聊天的总结配置
 */
const Settings = () => {
  const { currentRole, currentChat } = useChatBoxStore();
  const [settings, setSettings] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [saving, setSaving] = useState(false);

  // 加载设置
  useEffect(() => {
    if (currentRole && currentChat) {
      loadSettings();
    }
  }, [currentRole, currentChat]);

  const loadSettings = async () => {
    if (!currentRole || !currentChat) return;
    
    setLoading(true);
    setError(null);
    
    try {
      const response = await fetch(
        `/api/chats/${encodeURIComponent(currentRole)}/${encodeURIComponent(currentChat)}/summary-status`
      );
      
      if (!response.ok) {
        throw new Error('加载设置失败');
      }
      
      const data = await response.json();
      setSettings(data);
    } catch (err) {
      console.error('[Settings] 加载设置失败:', err);
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    if (!currentRole || !currentChat || !settings) return;
    
    setSaving(true);
    
    try {
      const response = await fetch(
        `/api/chats/${encodeURIComponent(currentRole)}/${encodeURIComponent(currentChat)}/settings`,
        {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(settings)
        }
      );
      
      if (!response.ok) {
        throw new Error('保存设置失败');
      }
      
      alert('设置已保存');
    } catch (err) {
      console.error('[Settings] 保存设置失败:', err);
      alert('保存失败: ' + err.message);
    } finally {
      setSaving(false);
    }
  };

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

  if (!currentRole || !currentChat) {
    return (
      <div className="settings-tab">
        <div className="settings-empty">
          <p>请先选择一个角色和聊天</p>
        </div>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="settings-tab">
        <div className="settings-loading">加载中...</div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="settings-tab">
        <div className="settings-error">
          <p>错误: {error}</p>
          <button onClick={loadSettings}>重试</button>
        </div>
      </div>
    );
  }

  return (
    <div className="settings-tab">
      <div className="settings-header">
        <h3>聊天设置</h3>
        <button 
          className="save-btn" 
          onClick={handleSave}
          disabled={saving}
        >
          {saving ? '保存中...' : '保存设置'}
        </button>
      </div>

      <div className="settings-content">
        {/* 历史记录模式 */}
        <div className="setting-group">
          <label className="setting-label">历史记录模式</label>
          <select
            className="setting-select"
            value={settings?.historyMode || 'full'}
            onChange={(e) => setSettings(prev => ({
              ...prev,
              historyMode: e.target.value
            }))}
            disabled={settings?.historyMode === 'rag'}
          >
            <option value="full">全量模式（保留所有消息）</option>
            <option value="summary">总结模式（定期总结历史）</option>
            <option value="rag" disabled>
              RAG模式（需要API配置，选择后不可取消）
            </option>
          </select>
          {settings?.historyMode === 'rag' && (
            <small className="setting-hint warning">
              ⚠️ RAG模式一旦选择不可取消
            </small>
          )}
        </div>

        {/* 总结配置（仅在summary模式下显示） */}
        {(settings?.historyMode === 'summary' || settings?.summaryConfig) && (
          <div className="setting-group">
            <label className="setting-label">总结配置</label>
            
            <div className="setting-row">
              <label>总结间隔（条）</label>
              <input
                type="number"
                min="2"
                value={settings?.summaryConfig?.interval || 10}
                onChange={(e) => updateSummaryConfig('interval', Number(e.target.value))}
              />
            </div>

            <div className="setting-row">
              <label>保留最近楼层</label>
              <input
                type="number"
                min="1"
                value={settings?.summaryConfig?.recentFloorsToKeep || 5}
                onChange={(e) => updateSummaryConfig('recentFloorsToKeep', Number(e.target.value))}
              />
            </div>

            <div className="setting-row checkbox-row">
              <label>
                <input
                  type="checkbox"
                  checked={settings?.summaryConfig?.includeUserInput !== false}
                  onChange={(e) => updateSummaryConfig('includeUserInput', e.target.checked)}
                />
                总结时包含用户输入
              </label>
            </div>

            <div className="setting-row">
              <label>总结提示词</label>
              <textarea
                value={settings?.summaryConfig?.summaryPrompt || '请总结以下对话内容，保留关键信息和上下文。'}
                onChange={(e) => updateSummaryConfig('summaryPrompt', e.target.value)}
                rows={3}
              />
            </div>

            <small className="setting-hint">
              💡 总结间隔：AI回复达到此数量时触发总结<br />
              保留楼层：最近X条不总结
            </small>
          </div>
        )}

        {/* 计数器状态 */}
        {settings?.historyMode === 'summary' && (
          <div className="setting-group status-group">
            <label className="setting-label">总结状态</label>
            <div className="status-info">
              <div className="status-item">
                <span className="status-label">当前计数:</span>
                <span className="status-value">{settings?.summaryCounter || 0}</span>
              </div>
              <div className="status-item">
                <span className="status-label">上次总结楼层:</span>
                <span className="status-value">L{settings?.lastSummaryFloor || 0}</span>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default Settings;
