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

interface ImageGenerateNodeProps {
  id: string;
  data: {
    prompt?: string;
    generatedImage?: string;
    result?: string;
  };
}

export const ImageGenerateNode: React.FC<ImageGenerateNodeProps> = ({ id, data }) => {
  const { processNode } = useNodeProcessing();
  const { status, progress } = useNodeStatus(id);

  const inputs: NodePort[] = [
    { id: 'prompt-input', type: 'text', label: '提示词输入', position: 'input' }
  ];

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

  // 监听输入数据变化并处理
  useEffect(() => {
    if (data.prompt && data.prompt !== data.result && status !== 'loading') {
      const inputData: DataFlow = {
        type: 'single',
        dataType: 'text',
        content: data.prompt
      };

      processNode(id, 'imageGenerate', inputData).catch(error => {
        console.error('Image generation failed:', error);
      });
    }
  }, [data.prompt, id, processNode, data.result, status]);

  return (
    <BaseNode
      id={id}
      title="图片生成"
      inputs={inputs}
      outputs={outputs}
    >
      <div className="space-y-2">
        {data.prompt && (
          <div className="text-xs text-gray-600">
            <div className="font-medium">提示词:</div>
            <div className="bg-gray-50 p-2 rounded text-xs max-h-16 overflow-y-auto">
              {data.prompt}
            </div>
          </div>
        )}
        
        {status === 'loading' && (
          <div className="text-xs text-blue-600 text-center">
            🎨 AI生成中... {Math.round(progress)}%
          </div>
        )}

        {data.result && status === 'success' && (
          <div className="space-y-2">
            <div className="text-xs font-medium text-green-600">生成结果:</div>
            <img 
              src={data.result} 
              alt="生成的图片" 
              className="w-full h-24 object-cover rounded border"
            />
          </div>
        )}
        
        {!data.prompt && (
          <div className="text-xs text-gray-400 text-center py-4">
            等待提示词输入...
          </div>
        )}
      </div>
    </BaseNode>
  );
};
