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

interface VideoGenerateNodeProps {
  id: string;
  data: {
    sourceImage?: string;
    motionPrompt?: string;
    generatedVideo?: string;
    settings?: {
      duration: number;
      fps: number;
      quality: 'low' | 'medium' | 'high';
    };
    result?: string;
  };
}

export const VideoGenerateNode: React.FC<VideoGenerateNodeProps> = ({ id, data }) => {
  const { processNode } = useNodeProcessing();
  const { status, progress } = useNodeStatus(id);
  const [motionPrompt, setMotionPrompt] = useState(data.motionPrompt || '');
  const [settings, setSettings] = useState({
    duration: data.settings?.duration || 3,
    fps: data.settings?.fps || 24,
    quality: data.settings?.quality || 'medium' as const
  });

  const inputs: NodePort[] = [
    { id: 'image-input', type: 'image', label: '源图片', position: 'input' },
    { id: 'motion-input', type: 'text', label: '运动描述', position: 'input' }
  ];

  const outputs: NodePort[] = [
    { id: 'video-output', type: 'video', label: '生成视频', position: 'output' }
  ];

  // 监听输入数据变化并处理
  useEffect(() => {
    if (data.sourceImage && motionPrompt && status !== 'loading') {
      const inputData: DataFlow = {
        type: 'single',
        dataType: 'image',
        content: {
          imageUrl: data.sourceImage,
          motionPrompt: motionPrompt,
          settings: settings
        }
      };
      
      processNode(id, 'videoGenerate', inputData).catch(error => {
        console.error('Video generation failed:', error);
      });
    }
  }, [data.sourceImage, motionPrompt, settings, id, processNode, status]);

  const qualityOptions = [
    { value: 'low', label: '低质量 (快速)', icon: '⚡' },
    { value: 'medium', label: '中等质量', icon: '⚖️' },
    { value: 'high', label: '高质量 (慢速)', icon: '💎' }
  ];

  return (
    <BaseNode
      id={id}
      title="视频生成"
      inputs={inputs}
      outputs={outputs}
      className="min-w-64"
    >
      <div className="space-y-3">
        {/* 运动描述输入 */}
        <div>
          <label className="text-xs font-medium text-gray-700 mb-1 block">运动描述</label>
          <textarea
            value={motionPrompt}
            onChange={(e) => setMotionPrompt(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>

        {/* 视频设置 */}
        <div className="grid grid-cols-2 gap-2">
          <div>
            <label className="text-xs font-medium text-gray-700 mb-1 block">时长(秒)</label>
            <input
              type="number"
              min="1"
              max="10"
              value={settings.duration}
              onChange={(e) => setSettings(prev => ({ ...prev, duration: parseInt(e.target.value) || 3 }))}
              className="w-full text-xs border border-gray-300 rounded px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500"
            />
          </div>
          <div>
            <label className="text-xs font-medium text-gray-700 mb-1 block">帧率</label>
            <select
              value={settings.fps}
              onChange={(e) => setSettings(prev => ({ ...prev, fps: parseInt(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"
            >
              <option value={12}>12 FPS</option>
              <option value={24}>24 FPS</option>
              <option value={30}>30 FPS</option>
            </select>
          </div>
        </div>

        {/* 质量选择 */}
        <div>
          <label className="text-xs font-medium text-gray-700 mb-1 block">质量</label>
          <select
            value={settings.quality}
            onChange={(e) => setSettings(prev => ({ ...prev, quality: e.target.value as any }))}
            className="w-full text-xs border border-gray-300 rounded px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500"
          >
            {qualityOptions.map(option => (
              <option key={option.value} value={option.value}>
                {option.icon} {option.label}
              </option>
            ))}
          </select>
        </div>

        {/* 源图片预览 */}
        {data.sourceImage && (
          <div>
            <div className="text-xs font-medium text-gray-700 mb-1">源图片:</div>
            <img 
              src={data.sourceImage} 
              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 className="text-xs text-gray-500 mt-1">
              预计需要 {settings.duration * 10} 秒
            </div>
          </div>
        )}
        
        {/* 生成结果 */}
        {data.result && status === 'success' && (
          <div>
            <div className="text-xs font-medium text-green-600 mb-1">生成结果:</div>
            <video 
              src={data.result} 
              controls 
              className="w-full h-24 rounded border"
              poster={data.sourceImage}
            >
              您的浏览器不支持视频播放
            </video>
          </div>
        )}
        
        {/* 等待输入提示 */}
        {!data.sourceImage && (
          <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>
  );
};
