import React, { useState, useCallback } from 'react';
import { BaseNode } from '../BaseNode';
import { NodePort } from '../../../types/canvas';
import { useCanvasStore } from '../../../store/canvasStore';

interface ImageUploadNodeProps {
  id: string;
  data: {
    image?: File | null;
    preview?: string;
    result?: string;
  };
}

export const ImageUploadNode: React.FC<ImageUploadNodeProps> = ({ id, data }) => {
  const [preview, setPreview] = useState(data.preview || '');
  const { updateNode } = useCanvasStore();

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

  const handleFileChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (event) => {
        const imageUrl = event.target?.result as string;
        setPreview(imageUrl);
        
        // 更新节点数据
        updateNode(id, {
          data: { 
            ...data, 
            image: file, 
            preview: imageUrl,
            result: imageUrl 
          }
        });
      };
      reader.readAsDataURL(file);
    }
  }, [id, data, updateNode]);

  return (
    <BaseNode
      id={id}
      title="图片上传"
      outputs={outputs}
    >
      <div className="space-y-2">
        <input
          type="file"
          accept="image/*"
          onChange={handleFileChange}
          className="w-full text-xs file:mr-2 file:py-1 file:px-2 file:rounded file:border-0 file:text-xs file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
        />
        
        {preview && (
          <div className="relative">
            <img 
              src={preview} 
              alt="预览" 
              className="w-full h-24 object-cover rounded border"
            />
            <div className="absolute top-1 right-1 bg-black/50 text-white text-xs px-1 rounded">
              预览
            </div>
          </div>
        )}
        
        {!preview && (
          <div className="w-full h-24 border-2 border-dashed border-gray-300 rounded flex items-center justify-center text-xs text-gray-400">
            点击上传图片
          </div>
        )}
      </div>
    </BaseNode>
  );
};
