import React, { useState, useRef } from 'react';
import { BaseNode } from '../BaseNode';
import { NodePort } from '../../../types/canvas';

interface VideoPlayerNodeProps {
  id: string;
  data: {
    videoUrl?: string;
    inputVideo?: string;
    result?: string;
  };
}

export const VideoPlayerNode: React.FC<VideoPlayerNodeProps> = ({ id, data }) => {
  const videoRef = useRef<HTMLVideoElement>(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [volume, setVolume] = useState(1);

  const inputs: NodePort[] = [
    { id: 'video-input', type: 'video', label: '视频输入', position: 'input' }
  ];

  const videoUrl = data.inputVideo || data.videoUrl || data.result;

  const handlePlayPause = () => {
    if (videoRef.current) {
      if (isPlaying) {
        videoRef.current.pause();
      } else {
        videoRef.current.play();
      }
      setIsPlaying(!isPlaying);
    }
  };

  const handleTimeUpdate = () => {
    if (videoRef.current) {
      setCurrentTime(videoRef.current.currentTime);
    }
  };

  const handleLoadedMetadata = () => {
    if (videoRef.current) {
      setDuration(videoRef.current.duration);
    }
  };

  const handleSeek = (e: React.ChangeEvent<HTMLInputElement>) => {
    const time = parseFloat(e.target.value);
    if (videoRef.current) {
      videoRef.current.currentTime = time;
      setCurrentTime(time);
    }
  };

  const handleVolumeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const vol = parseFloat(e.target.value);
    setVolume(vol);
    if (videoRef.current) {
      videoRef.current.volume = vol;
    }
  };

  const formatTime = (time: number) => {
    const minutes = Math.floor(time / 60);
    const seconds = Math.floor(time % 60);
    return `${minutes}:${seconds.toString().padStart(2, '0')}`;
  };

  const downloadVideo = () => {
    if (videoUrl) {
      const link = document.createElement('a');
      link.href = videoUrl;
      link.download = `video_${Date.now()}.mp4`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  };

  return (
    <BaseNode
      id={id}
      title="视频播放器"
      inputs={inputs}
      className="min-w-80"
    >
      <div className="space-y-3">
        {videoUrl ? (
          <>
            {/* 视频播放区域 */}
            <div className="relative bg-black rounded overflow-hidden">
              <video
                ref={videoRef}
                src={videoUrl}
                className="w-full h-48 object-contain"
                onTimeUpdate={handleTimeUpdate}
                onLoadedMetadata={handleLoadedMetadata}
                onPlay={() => setIsPlaying(true)}
                onPause={() => setIsPlaying(false)}
                onEnded={() => setIsPlaying(false)}
              />
              
              {/* 播放按钮覆盖层 */}
              <div className="absolute inset-0 flex items-center justify-center bg-black bg-opacity-30 opacity-0 hover:opacity-100 transition-opacity">
                <button
                  onClick={handlePlayPause}
                  className="bg-white bg-opacity-80 rounded-full p-3 hover:bg-opacity-100 transition-all"
                >
                  {isPlaying ? (
                    <svg className="w-6 h-6" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zM7 8a1 1 0 012 0v4a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v4a1 1 0 102 0V8a1 1 0 00-1-1z" clipRule="evenodd" />
                    </svg>
                  ) : (
                    <svg className="w-6 h-6" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z" clipRule="evenodd" />
                    </svg>
                  )}
                </button>
              </div>
            </div>

            {/* 控制栏 */}
            <div className="space-y-2">
              {/* 进度条 */}
              <div className="flex items-center space-x-2 text-xs">
                <span className="text-gray-500 min-w-10">{formatTime(currentTime)}</span>
                <input
                  type="range"
                  min="0"
                  max={duration || 0}
                  value={currentTime}
                  onChange={handleSeek}
                  className="flex-1 h-1 bg-gray-200 rounded-lg appearance-none cursor-pointer"
                />
                <span className="text-gray-500 min-w-10">{formatTime(duration)}</span>
              </div>

              {/* 控制按钮 */}
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-2">
                  <button
                    onClick={handlePlayPause}
                    className="text-blue-600 hover:text-blue-800 transition-colors"
                  >
                    {isPlaying ? '⏸️' : '▶️'}
                  </button>
                  
                  {/* 音量控制 */}
                  <div className="flex items-center space-x-1">
                    <span className="text-xs">🔊</span>
                    <input
                      type="range"
                      min="0"
                      max="1"
                      step="0.1"
                      value={volume}
                      onChange={handleVolumeChange}
                      className="w-16 h-1 bg-gray-200 rounded-lg appearance-none cursor-pointer"
                    />
                  </div>
                </div>

                {/* 下载按钮 */}
                <button
                  onClick={downloadVideo}
                  className="text-xs text-green-600 hover:text-green-800 transition-colors px-2 py-1 border border-green-300 rounded hover:bg-green-50"
                >
                  📥 下载
                </button>
              </div>
            </div>

            {/* 视频信息 */}
            <div className="text-xs text-gray-500 bg-gray-50 p-2 rounded">
              <div>时长: {formatTime(duration)}</div>
              <div className="truncate">URL: {videoUrl}</div>
            </div>
          </>
        ) : (
          <div className="text-xs text-gray-400 text-center py-12 border-2 border-dashed border-gray-300 rounded">
            等待视频输入...
          </div>
        )}
      </div>
    </BaseNode>
  );
};
