import React, { useState, useEffect } from 'react';
import { useTableStore } from '../../../../Store/SideBarRight';
import './Table.css';

const Table = () => {
  // ✅ 从 Zustand store 获取状态和方法
  const { 
    tableHeaders,
    tableDefaults,
    isLoading,
    currentRole,
    currentChat,
    loadTags,
    refresh,
    updateTableData  // ✅ 新增：保存方法
  } = useTableStore();

  // 本地编辑状态
  const [editingValues, setEditingValues] = useState({});
  const [isSaving, setIsSaving] = useState(false);

  // 监听角色/聊天变化，自动加载数据
  useEffect(() => {
    if (currentRole) {
      loadTags(currentRole, currentChat);
      setEditingValues({}); // 重置编辑状态
    }
  }, [currentRole, currentChat, loadTags]);

  // ✅ 处理值变化
  const handleValueChange = (key, value) => {
    setEditingValues(prev => ({
      ...prev,
      [key]: value
    }));
  };

  // ✅ 保存单个字段（失焦时自动保存）
  const handleBlur = async (key) => {
    const newValue = editingValues[key];
    if (newValue === undefined || newValue === tableDefaults[key]) {
      return; // 没有变化，不保存
    }

    setIsSaving(true);
    
    // 更新 tableDefaults
    const newTableDefaults = {
      ...tableDefaults,
      [key]: newValue
    };

    await updateTableData({ tableDefaults: newTableDefaults });
    
    // 清除编辑状态
    setEditingValues(prev => {
      const newState = { ...prev };
      delete newState[key];
      return newState;
    });
    
    setIsSaving(false);
  };

  // ✅ 按 Enter 键保存
  const handleKeyDown = (e, key) => {
    if (e.key === 'Enter') {
      e.target.blur(); // 触发 blur 事件
    }
  };

  // 如果没有角色，显示提示
  if (!currentRole) {
    return (
      <div className="table-panel">
        <div className="tab-header">
          <span className="title-text">动态表格</span>
        </div>
        <div className="empty-table">
          <p>📊</p>
          <p>请选择一个角色</p>
        </div>
      </div>
    );
  }

  // ✅ 如果有动态表格数据，显示键值对表格
  if (tableHeaders.length > 0) {
    return (
      <div className="table-panel">
        <div className="tab-header">
          <span className="title-text">动态表格</span>
          <div className="header-actions">
            <span className="table-info">
              {tableHeaders.length} 个字段 {isSaving && '💾'}
            </span>
            <button 
              className="refresh-btn"
              onClick={refresh}
              disabled={isLoading || isSaving}
              title="刷新数据"
            >
              {isLoading ? '⏳' : '🔄'}
            </button>
          </div>
        </div>

        <div className="table-container">
          {/* ✅ 动态表格 - 可编辑的键值对展示 */}
          <div className="dynamic-table">
            {tableHeaders.map((header, index) => {
              const currentValue = editingValues[header] !== undefined 
                ? editingValues[header] 
                : (tableDefaults[header] !== undefined ? tableDefaults[header] : '');
              
              return (
                <div key={index} className="table-row">
                  <div className="table-key">
                    {header}
                  </div>
                  <div className="table-value">
                    <input
                      type="text"
                      className="table-input"
                      value={currentValue}
                      onChange={(e) => handleValueChange(header, e.target.value)}
                      onBlur={() => handleBlur(header)}
                      onKeyDown={(e) => handleKeyDown(e, header)}
                      placeholder="输入值..."
                    />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    );
  }

  // ✅ 否则显示空状态
  return (
    <div className="table-panel">
      <div className="tab-header">
        <span className="title-text">动态表格</span>
      </div>
      <div className="empty-table">
        <p>📊</p>
        <p>该角色没有动态表格数据</p>
      </div>
    </div>
  );
};

export default Table;
