import React, { useEffect, useState } from 'react';
import { BaseNode } from '../BaseNode';
import { NodePort, DataFlow } from '../../../types/canvas';
import { useNodeProcessing, useNodeStatus } from '../../../hooks/useNodeProcessing';

interface ImageEditNodeProps {
  id: string;
  data: {
    originalImage?: string;
    editedImage?: string;
    editInstruction?: string;
    editType?: 'style-transfer' | 'background-remove' | 'enhance' | 'resize';
    result?: string;
  };
}

export const ImageEditNode: React.FC<ImageEditNodeProps> = ({ id, data }) => {
  const { processNode } = useNodeProcessing();
  const { status, progress } = useNodeStatus(id);
  const [editType, setEditType] = useState<string>(data.editType || 'enhance');
  const [instruction, setInstruction] = useState(data.editInstruction || '');

  const inputs: NodePort[] = [
    { id: 'image-input', type: 'image', label: '原始图片', position: 'input' },
    { id: 'instruction-input', type: 'text', label: '编辑指令', position: 'input' }
  ];

  const outputs: NodePort[] = [
    { id: 'image-output', type: 'image', label: '编辑后图片', position: 'output' }
  ];

  // 监听输入数据变化并处理
  useEffect(() => {
    if (data.originalImage && instruction && status !== 'loading') {
      const inputData: DataFlow = {
        type: 'single',
        dataType: 'image',
        content: {
          imageUrl: data.originalImage,
          instruction: instruction,
          editType: editType
        }
      };
      
      processNode(id, 'imageEdit', inputData).catch(error => {
        console.error('Image editing failed:', error);
      });
    }
  }, [data.originalImage, instruction, editType, id, processNode, status]);

  const editTypeOptions = [
    { value: 'enhance', label: '图片增强', icon: '✨' },
    { value: 'style-transfer', label: '风格转换', icon: '🎨' },
    { value: 'background-remove', label: '背景移除', icon: '🖼️' },
    { value: 'resize', label: '尺寸调整', icon: '📐' }
  ];

  return (
    <BaseNode
      id={id}
      title="图片编辑"
      inputs={inputs}
      outputs={outputs}
    >
      <div className="space-y-3">
        {/* 编辑类型选择 */}
        <div>
          <label className="text-xs font-medium text-gray-700 mb-1 block">编辑类型</label>
          <select
            value={editType}
            onChange={(e) => setEditType(e.target.value)}
            className="w-full text-xs border border-gray-300 rounded px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500"
          >
            {editTypeOptions.map(option => (
              <option key={option.value} value={option.value}>
                {option.icon} {option.label}
              </option>
            ))}
          </select>
        </div>

        {/* 编辑指令输入 */}
        <div>
          <label className="text-xs font-medium text-gray-700 mb-1 block">编辑指令</label>
          <textarea
            value={instruction}
            onChange={(e) => setInstruction(e.target.value)}
            placeholder="描述你想要的编辑效果..."
            className="w-full h-16 text-xs border border-gray-300 rounded px-2 py-1 resize-none focus:outline-none focus:ring-1 focus:ring-blue-500"
          />
        </div>

        {/* 原始图片预览 */}
        {data.originalImage && (
          <div>
            <div className="text-xs font-medium text-gray-700 mb-1">原始图片:</div>
            <img 
              src={data.originalImage} 
              alt="原始图片" 
              className="w-full h-20 object-cover rounded border"
            />
          </div>
        )}
        
        {/* 处理状态 */}
        {status === 'loading' && (
          <div className="text-xs text-blue-600 text-center">
            ✏️ 编辑中... {Math.round(progress)}%
          </div>
        )}
        
        {/* 编辑结果 */}
        {data.result && status === 'success' && (
          <div>
            <div className="text-xs font-medium text-green-600 mb-1">编辑结果:</div>
            <img 
              src={data.result} 
              alt="编辑后的图片" 
              className="w-full h-24 object-cover rounded border"
            />
          </div>
        )}
        
        {/* 等待输入提示 */}
        {!data.originalImage && (
          <div className="text-xs text-gray-400 text-center py-4">
            等待图片输入...
          </div>
        )}

        {/* 错误状态 */}
        {status === 'error' && (
          <div className="text-xs text-red-600 bg-red-50 p-2 rounded">
            编辑失败，请检查输入并重试
          </div>
        )}
      </div>
    </BaseNode>
  );
};
