import React, { useState, useEffect } from 'react';
import './TaskPlanner.css';
import { deviceParameters, DeviceCategory, AttributeGroup } from '../../data/deviceParameters';
import { ExtractedStep } from '../../services/api';

interface TaskPlannerProps {
  extractedSteps?: ExtractedStep[];
}

const TaskPlanner: React.FC<TaskPlannerProps> = ({ extractedSteps = [] }) => {
  // 任务标题
  const [taskTitle, setTaskTitle] = useState('新建任务规划');
  // 消息提示
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  // 当前选中的步骤
  const [selectedStep, setSelectedStep] = useState<ExtractedStep | null>(null);

  // 当前选中的设备分类
  const [selectedDevice, setSelectedDevice] = useState<DeviceCategory | null>(
    deviceParameters.length > 0 ? deviceParameters[0] : null
  );

  // 折叠状态
  const [collapsedGroups, setCollapsedGroups] = useState<{ [key: string]: boolean }>({});

  // 参数值状态（步骤ID -> 设备类别 -> 参数名 -> 值）
  const [paramValues, setParamValues] = useState<{
    [stepId: number]: {
      [deviceCategory: string]: {
        [paramName: string]: string;
      };
    };
  }>({});

  // 过滤掉空值的参数对象
  const filterEmptyParams = (
    params: { [param: string]: string }
  ): { [param: string]: string } => {
    const filtered: { [param: string]: string } = {};
    for (const [key, value] of Object.entries(params)) {
      if (value && typeof value === 'string' && value.trim().length > 0) {
        filtered[key] = value;
      }
    }
    return filtered;
  };

  // 深度合并两个设备参数对象（忽略空值和空对象）
  const mergeDeviceParams = (
    base: { [device: string]: { [param: string]: string } },
    overlay: { [device: string]: { [param: string]: string } }
  ): { [device: string]: { [param: string]: string } } => {
    const result = { ...base };
    for (const deviceCategory of Object.keys(overlay)) {
      const overlayParams = overlay[deviceCategory];
      // 跳过空对象
      if (!overlayParams || Object.keys(overlayParams).length === 0) {
        continue;
      }
      // 过滤掉空值
      const filteredOverlay = filterEmptyParams(overlayParams);
      if (Object.keys(filteredOverlay).length === 0) {
        continue;
      }
      // 合并非空参数
      const baseParams = result[deviceCategory] || {};
      result[deviceCategory] = {
        ...baseParams,
        ...filteredOverlay
      };
    }
    return result;
  };

  // 当 extractedSteps 变化时，初始化参数值（带累积继承）
  useEffect(() => {
    if (extractedSteps.length > 0) {
      // 初始化参数值，参数在步骤之间累积继承
      const initialValues: typeof paramValues = {};
      let accumulatedParams: { [device: string]: { [param: string]: string } } = {};
      
      extractedSteps.forEach(step => {
        // 当前步骤的参数 = 之前累积的参数 + 当前步骤新增/修改的参数
        accumulatedParams = mergeDeviceParams(accumulatedParams, step.deviceParams);
        // 深拷贝累积参数到当前步骤
        initialValues[step.id] = JSON.parse(JSON.stringify(accumulatedParams));
      });
      
      setParamValues(initialValues);
      
      // 选中第一个步骤
      setSelectedStep(extractedSteps[0]);
    } else {
      setSelectedStep(null);
      setParamValues({});
    }
  }, [extractedSteps]);

  const showMessage = (type: 'success' | 'error', text: string) => {
    setMessage({ type, text });
    setTimeout(() => setMessage(null), 3000);
  };

  // 选择步骤
  const handleStepSelect = (step: ExtractedStep) => {
    setSelectedStep(step);
  };

  // 切换设备分类
  const handleDeviceSelect = (device: DeviceCategory) => {
    setSelectedDevice(device);
    setCollapsedGroups({});
  };

  // 切换组折叠状态
  const toggleGroup = (groupName: string) => {
    setCollapsedGroups(prev => ({
      ...prev,
      [groupName]: !prev[groupName]
    }));
  };

  // 获取参数值
  const getParamValue = (attrName: string): string => {
    if (!selectedStep || !selectedDevice) return '';
    const stepParams = paramValues[selectedStep.id];
    if (!stepParams) return '';
    const deviceParams = stepParams[selectedDevice.category];
    if (!deviceParams) return '';
    return deviceParams[attrName] || '';
  };

  // 更新参数值
  const updateParamValue = (attrName: string, value: string) => {
    if (!selectedStep || !selectedDevice) return;
    
    setParamValues(prev => ({
      ...prev,
      [selectedStep.id]: {
        ...prev[selectedStep.id],
        [selectedDevice.category]: {
          ...(prev[selectedStep.id]?.[selectedDevice.category] || {}),
          [attrName]: value
        }
      }
    }));
  };

  // 检查当前步骤是否有该设备的非空参数
  const hasDeviceParams = (deviceCategory: string): boolean => {
    if (!selectedStep) return false;
    const stepParams = paramValues[selectedStep.id];
    if (!stepParams) return false;
    const deviceParams = stepParams[deviceCategory];
    if (!deviceParams || typeof deviceParams !== 'object') return false;
    
    // 检查是否有任何非空值（排除空字符串、null、undefined）
    const values = Object.values(deviceParams);
    if (values.length === 0) return false;
    
    return values.some(value => {
      if (value === null || value === undefined) return false;
      if (typeof value === 'string') return value.trim().length > 0;
      return true;
    });
  };

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

      {/* 标题行 */}
      <div className="planner-title-row">
        <input
          type="text"
          className="planner-title selectable"
          value={taskTitle}
          onChange={(e) => setTaskTitle(e.target.value)}
          placeholder="请输入任务名称..."
        />
        <button 
          className="complete-btn"
          onClick={() => showMessage('success', '任务规划已完成')}
          title="完成规划并提交到下一流程"
        >
          <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" />
            <polyline points="22 4 12 14.01 9 11.01" />
          </svg>
          完成规划
        </button>
      </div>

      {/* 主体区域 - 三栏布局 */}
      <div className="planner-body">
        {/* 左侧：动态步骤列表 */}
        <div className="planner-steps">
          <div className="panel-header">
            测试步骤
            {extractedSteps.length > 0 && (
              <span className="step-count">({extractedSteps.length})</span>
            )}
          </div>
          <div className="steps-list">
            {extractedSteps.length > 0 ? (
              extractedSteps.map((step) => (
                <div
                  key={step.id}
                  className={`step-item ${selectedStep?.id === step.id ? 'active' : ''}`}
                  onClick={() => handleStepSelect(step)}
                >
                  <span className="step-number">步骤 {step.id}</span>
                  <span className="step-name">{step.name}</span>
                </div>
              ))
            ) : (
              <div className="empty-state-vertical">
                <svg viewBox="0 0 24 24" width="32" height="32" fill="none" stroke="currentColor" strokeWidth="1.5">
                  <path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2" />
                  <rect x="9" y="3" width="6" height="4" rx="1" />
                  <path d="M9 12h6M9 16h6" />
                </svg>
                <span>暂无测试步骤</span>
                <span className="hint">请先在意图编制中完成编制</span>
              </div>
            )}
          </div>
        </div>

        {/* 中间：设备分类列表 */}
        <div className="planner-categories">
          <div className="panel-header">
            {selectedStep ? `仪器配置` : '仪器配置'}
          </div>
          <div className="categories-list">
            {deviceParameters.map((device) => (
              <div
                key={device.category}
                className={`category-item ${selectedDevice?.category === device.category ? 'active' : ''} ${hasDeviceParams(device.category) ? 'has-params' : ''}`}
                onClick={() => handleDeviceSelect(device)}
              >
                <span className="category-title">{device.category}</span>
                {hasDeviceParams(device.category) && (
                  <span className="has-data-badge">已配置</span>
                )}
              </div>
            ))}
          </div>
        </div>

        {/* 右侧：参数详情 */}
        <div className="planner-params">
          {selectedDevice ? (
            <>
              <div className="panel-header">{selectedDevice.category}</div>
              <div className="params-content">
                {selectedDevice.groups.map((group) => {
                  const isCollapsed = collapsedGroups[group.name];
                  return (
                    <div key={group.name} className={`group-panel ${isCollapsed ? 'collapsed' : ''}`}>
                      <div 
                        className="group-header" 
                        onClick={() => toggleGroup(group.name)}
                      >
                        {group.name}
                      </div>
                      <div className="group-body">
                        {/* 表头 */}
                        <div className="attr-table-header">
                          <div className="col-name">属性名</div>
                          <div className="col-desc">说明</div>
                          <div className="col-value">属性值</div>
                        </div>
                        {/* 属性行 */}
                        {group.attributes.map((attr) => (
                          <div key={attr} className="attr-row">
                            <div className="col-name">{attr}</div>
                            <div className="col-desc">-</div>
                            <div className="col-value">
                              <input 
                                type="text" 
                                className="attr-input" 
                                value={getParamValue(attr)}
                                onChange={(e) => updateParamValue(attr, e.target.value)}
                                placeholder="请输入..." 
                                disabled={!selectedStep}
                              />
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  );
                })}
              </div>
            </>
          ) : (
            <>
              <div className="panel-header">参数详情</div>
              <div className="empty-state">请选择仪器类型</div>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

export default TaskPlanner;
