import React, { useState, useEffect } from 'react';
import { 
  Settings, 
  Link, 
  Unlink, 
  AlertCircle, 
  Info,
  Search,
  ChevronDown,
  ChevronRight
} from 'lucide-react';
import { NodeMapping } from '../../types/workflow';

interface NodeMappingEditorProps {
  /** 当前的节点映射配置 */
  mapping?: NodeMapping;
  /** 映射配置变化回调 */
  onMappingChange: (mapping: NodeMapping | undefined) => void;
  /** ComfyUI工作流JSON，用于提取可用节点 */
  workflowJson: any;
  /** 字段名称，用于显示 */
  fieldName: string;
  /** 字段类型，用于推荐合适的转换类型 */
  fieldType: string;
  /** 是否只读 */
  readonly?: boolean;
}

interface WorkflowNode {
  id: string;
  class_type: string;
  title?: string;
  inputs: Record<string, any>;
}

export const NodeMappingEditor: React.FC<NodeMappingEditorProps> = ({
  mapping,
  onMappingChange,
  workflowJson,
  fieldName,
  fieldType,
  readonly = false
}) => {
  const [isExpanded, setIsExpanded] = useState(false);
  const [availableNodes, setAvailableNodes] = useState<WorkflowNode[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedNodeInputs, setSelectedNodeInputs] = useState<string[]>([]);

  // 解析工作流JSON，提取可用节点
  useEffect(() => {
    if (workflowJson && typeof workflowJson === 'object') {
      const nodes: WorkflowNode[] = [];

      try {
        Object.entries(workflowJson).forEach(([nodeId, nodeData]: [string, any]) => {
          if (nodeData && typeof nodeData === 'object') {
            const node: WorkflowNode = {
              id: String(nodeId),
              class_type: String(nodeData.class_type || 'Unknown'),
              title: nodeData._meta?.title ? String(nodeData._meta.title) : undefined,
              inputs: (nodeData.inputs && typeof nodeData.inputs === 'object') ? nodeData.inputs : {}
            };
            nodes.push(node);
          }
        });
      } catch (error) {
        console.error('解析工作流JSON时出错:', error);
      }

      setAvailableNodes(nodes);
    } else {
      setAvailableNodes([]);
    }
  }, [workflowJson]);

  // 当选择的节点改变时，更新可用的输入字段
  useEffect(() => {
    if (mapping?.node_id) {
      const selectedNode = availableNodes.find(node => node.id === mapping.node_id);
      if (selectedNode && selectedNode.inputs) {
        // 确保只获取字符串类型的键
        const inputKeys = Object.keys(selectedNode.inputs).filter(key =>
          typeof key === 'string' && key.trim().length > 0
        );
        setSelectedNodeInputs(inputKeys);
      } else {
        setSelectedNodeInputs([]);
      }
    } else {
      setSelectedNodeInputs([]);
    }
  }, [mapping?.node_id, availableNodes]);

  // 过滤节点
  const filteredNodes = availableNodes.filter(node => {
    const searchLower = searchTerm.toLowerCase();
    const nodeId = String(node.id || '').toLowerCase();
    const classType = String(node.class_type || '').toLowerCase();
    const title = String(node.title || '').toLowerCase();

    return nodeId.includes(searchLower) ||
           classType.includes(searchLower) ||
           title.includes(searchLower);
  });

  // 根据字段类型推荐转换类型
  const getRecommendedTransformTypes = (fieldType: string): string[] => {
    switch (fieldType) {
      case 'text':
      case 'textarea':
        return ['string'];
      case 'number':
      case 'slider':
        return ['number', 'string'];
      case 'checkbox':
        return ['boolean', 'string'];
      case 'select':
        return ['string', 'array'];
      case 'image_upload':
      case 'file_upload':
        return ['file_url', 'string'];
      default:
        return ['string', 'number', 'boolean'];
    }
  };

  const transformTypes = [
    { value: 'string', label: '字符串', description: '转换为文本格式' },
    { value: 'number', label: '数字', description: '转换为数值格式' },
    { value: 'boolean', label: '布尔值', description: '转换为真/假值' },
    { value: 'array', label: '数组', description: '转换为数组格式' },
    { value: 'object', label: '对象', description: '保持对象格式' },
    { value: 'file_url', label: '文件URL', description: '转换为CDN文件链接' }
  ];

  const recommendedTypes = getRecommendedTransformTypes(fieldType);

  const updateMapping = (updates: Partial<NodeMapping>) => {
    if (mapping) {
      onMappingChange({ ...mapping, ...updates });
    } else {
      onMappingChange({
        node_id: '',
        input_field: '',
        transform_type: 'string',
        required: false,
        ...updates
      });
    }
  };

  const clearMapping = () => {
    onMappingChange(undefined);
  };

  return (
    <div className="border border-gray-200 rounded-lg">
      {/* 头部 */}
      <div className="p-3 bg-gray-50 border-b border-gray-200">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-2">
            <button
              onClick={() => setIsExpanded(!isExpanded)}
              className="text-gray-500 hover:text-gray-700"
              disabled={readonly}
            >
              {isExpanded ? (
                <ChevronDown className="w-4 h-4" />
              ) : (
                <ChevronRight className="w-4 h-4" />
              )}
            </button>
            
            {mapping ? (
              <Link className="w-4 h-4 text-green-500" />
            ) : (
              <Unlink className="w-4 h-4 text-gray-400" />
            )}
            
            <span className="text-sm font-medium text-gray-700">
              节点映射配置
            </span>
            
            {mapping && (
              <span className="text-xs text-green-600 bg-green-100 px-2 py-1 rounded">
                已配置
              </span>
            )}
          </div>

          {!readonly && mapping && (
            <button
              onClick={clearMapping}
              className="text-xs text-red-600 hover:text-red-700"
            >
              清除映射
            </button>
          )}
        </div>

        {mapping && (
          <div className="mt-2 text-xs text-gray-600">
            映射到节点: <code className="bg-gray-200 px-1 rounded">{String(mapping.node_id)}</code>
            {mapping.input_field && (
              <>
                {' → '}
                <code className="bg-gray-200 px-1 rounded">{String(mapping.input_field)}</code>
              </>
            )}
          </div>
        )}
      </div>

      {/* 配置内容 */}
      {isExpanded && (
        <div className="p-4 space-y-4">
          {/* 节点选择 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              目标节点
            </label>
            
            {/* 搜索框 */}
            <div className="relative mb-2">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
              <input
                type="text"
                placeholder="搜索节点..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
                disabled={readonly}
              />
            </div>

            {/* 节点列表 */}
            <div className="max-h-40 overflow-y-auto border border-gray-300 rounded-lg">
              {filteredNodes.map((node) => (
                <button
                  key={node.id}
                  onClick={() => updateMapping({ node_id: node.id })}
                  disabled={readonly}
                  className={`w-full text-left p-3 border-b border-gray-200 last:border-b-0 hover:bg-gray-50 transition-colors ${
                    mapping?.node_id === node.id ? 'bg-blue-50 border-blue-200' : ''
                  }`}
                >
                  <div className="flex items-center justify-between">
                    <div>
                      <div className="text-sm font-medium text-gray-900">
                        {String(node.title || node.id)}
                      </div>
                      <div className="text-xs text-gray-500">
                        ID: {String(node.id)} | 类型: {String(node.class_type)}
                      </div>
                    </div>
                    {mapping?.node_id === node.id && (
                      <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
                    )}
                  </div>
                </button>
              ))}
              
              {filteredNodes.length === 0 && (
                <div className="p-3 text-center text-gray-500 text-sm">
                  没有找到匹配的节点
                </div>
              )}
            </div>
          </div>

          {/* 输入字段选择 */}
          {mapping?.node_id && selectedNodeInputs.length > 0 && (
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                输入字段
              </label>
              <select
                value={mapping.input_field || ''}
                onChange={(e) => updateMapping({ input_field: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
                disabled={readonly}
              >
                <option value="">请选择输入字段</option>
                {selectedNodeInputs.map((inputField) => (
                  <option key={String(inputField)} value={String(inputField)}>
                    {String(inputField)}
                  </option>
                ))}
              </select>
            </div>
          )}

          {/* 数据转换类型 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              数据转换类型
            </label>
            <select
              value={mapping?.transform_type || 'string'}
              onChange={(e) => updateMapping({ transform_type: e.target.value as any })}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
              disabled={readonly}
            >
              {transformTypes.map((type) => (
                <option key={type.value} value={type.value}>
                  {type.label}
                  {recommendedTypes.includes(type.value) && ' (推荐)'}
                </option>
              ))}
            </select>
            
            {mapping?.transform_type && (
              <div className="mt-1 text-xs text-gray-600">
                {transformTypes.find(t => t.value === mapping.transform_type)?.description}
              </div>
            )}
          </div>

          {/* 默认值 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              默认值 (可选)
            </label>
            <input
              type="text"
              value={mapping?.default_value !== undefined ?
                (typeof mapping.default_value === 'string' ?
                  mapping.default_value :
                  JSON.stringify(mapping.default_value)
                ) : ''
              }
              onChange={(e) => {
                try {
                  const value = e.target.value ? JSON.parse(e.target.value) : undefined;
                  updateMapping({ default_value: value });
                } catch {
                  // 如果不是有效的JSON，保存为字符串
                  updateMapping({ default_value: e.target.value || undefined });
                }
              }}
              placeholder="留空则使用字段默认值"
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
              disabled={readonly}
            />
            <div className="mt-1 text-xs text-gray-500">
              支持JSON格式，如: "文本"、123、true、["选项1", "选项2"]
            </div>
          </div>

          {/* 必需选项 */}
          <div>
            <label className="flex items-center space-x-2">
              <input
                type="checkbox"
                checked={mapping?.required || false}
                onChange={(e) => updateMapping({ required: e.target.checked })}
                className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                disabled={readonly}
              />
              <span className="text-sm text-gray-700">必需映射</span>
            </label>
            <div className="mt-1 text-xs text-gray-500">
              如果字段为空且没有默认值，执行时将报错
            </div>
          </div>

          {/* 提示信息 */}
          <div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
            <div className="flex items-start space-x-2">
              <Info className="w-4 h-4 text-blue-500 mt-0.5" />
              <div className="text-sm text-blue-700">
                <div className="font-medium mb-1">映射说明</div>
                <ul className="text-xs space-y-1">
                  <li>• 选择ComfyUI工作流中的目标节点和输入字段</li>
                  <li>• 根据字段类型选择合适的数据转换方式</li>
                  <li>• 可设置默认值，当用户未填写时使用</li>
                  <li>• 必需映射确保关键字段不会为空</li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
