import React, { useRef, useEffect, useState } from 'react'
import { Play, Pause, Volume2, Maximize2, RotateCcw } from 'lucide-react'
import { useMediaStore } from '../stores/useMediaStore'
import { useProjectStore } from '../stores/useProjectStore'

interface VideoPreviewProps {
  className?: string
}

const VideoPreview: React.FC<VideoPreviewProps> = ({ className = '' }) => {
  const videoRef = useRef<HTMLVideoElement>(null)
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const [isFullscreen, setIsFullscreen] = useState(false)
  const [showControls, setShowControls] = useState(true)
  const [controlsTimeout, setControlsTimeout] = useState<NodeJS.Timeout | null>(null)

  const { 
    currentMedia,
    isPlaying, 
    currentTime, 
    duration, 
    volume,
    setPlaying, 
    setCurrentTime, 
    setDuration,
    setVolume 
  } = useMediaStore()

  const { currentProject } = useProjectStore()

  // Handle video loading
  useEffect(() => {
    if (videoRef.current && currentMedia) {
      videoRef.current.src = currentMedia
      videoRef.current.load()
    }
  }, [currentMedia])

  // Handle play/pause
  useEffect(() => {
    if (videoRef.current) {
      if (isPlaying) {
        videoRef.current.play()
      } else {
        videoRef.current.pause()
      }
    }
  }, [isPlaying])

  // Handle time updates
  useEffect(() => {
    if (videoRef.current) {
      videoRef.current.currentTime = currentTime
    }
  }, [currentTime])

  // Handle volume changes
  useEffect(() => {
    if (videoRef.current) {
      videoRef.current.volume = volume
    }
  }, [volume])

  // Video event handlers
  const handleLoadedMetadata = () => {
    if (videoRef.current) {
      setDuration(videoRef.current.duration)
    }
  }

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

  const handlePlay = () => {
    setPlaying(true)
  }

  const handlePause = () => {
    setPlaying(false)
  }

  const handleVolumeChange = () => {
    if (videoRef.current) {
      setVolume(videoRef.current.volume)
    }
  }

  // Control visibility
  const showControlsTemporarily = () => {
    setShowControls(true)
    
    if (controlsTimeout) {
      clearTimeout(controlsTimeout)
    }
    
    const timeout = setTimeout(() => {
      if (isPlaying) {
        setShowControls(false)
      }
    }, 3000)
    
    setControlsTimeout(timeout)
  }

  const handleMouseMove = () => {
    showControlsTemporarily()
  }

  const handleMouseLeave = () => {
    if (isPlaying) {
      setShowControls(false)
    }
  }

  // Fullscreen handling
  const toggleFullscreen = () => {
    if (!document.fullscreenElement) {
      videoRef.current?.requestFullscreen()
      setIsFullscreen(true)
    } else {
      document.exitFullscreen()
      setIsFullscreen(false)
    }
  }

  // Format time for display
  const formatTime = (seconds: number): string => {
    const mins = Math.floor(seconds / 60)
    const secs = Math.floor(seconds % 60)
    return `${mins}:${secs.toString().padStart(2, '0')}`
  }

  // Handle seeking
  const handleSeek = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newTime = parseFloat(e.target.value)
    setCurrentTime(newTime)
  }

  return (
    <div 
      className={`relative bg-black rounded-lg overflow-hidden ${className}`}
      onMouseMove={handleMouseMove}
      onMouseLeave={handleMouseLeave}
    >
      {/* Video Element */}
      <video
        ref={videoRef}
        className="w-full h-full object-contain"
        onLoadedMetadata={handleLoadedMetadata}
        onTimeUpdate={handleTimeUpdate}
        onPlay={handlePlay}
        onPause={handlePause}
        onVolumeChange={handleVolumeChange}
        onClick={() => setPlaying(!isPlaying)}
      />

      {/* Canvas for effects preview */}
      <canvas
        ref={canvasRef}
        className="absolute inset-0 w-full h-full object-contain pointer-events-none"
        style={{ display: 'none' }}
      />

      {/* No video placeholder */}
      {!currentMedia && (
        <div className="absolute inset-0 flex items-center justify-center text-white">
          <div className="text-center">
            <div className="w-24 h-24 bg-secondary-700 rounded-full flex items-center justify-center mb-4 mx-auto">
              <Play size={32} />
            </div>
            <p className="text-secondary-400">选择视频文件开始预览</p>
          </div>
        </div>
      )}

      {/* Video Controls Overlay */}
      {currentMedia && (
        <div 
          className={`absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-transparent transition-opacity duration-300 ${
            showControls ? 'opacity-100' : 'opacity-0'
          }`}
        >
          {/* Top Controls */}
          <div className="absolute top-4 right-4 flex items-center space-x-2">
            <button
              onClick={toggleFullscreen}
              className="w-10 h-10 bg-black/50 hover:bg-black/70 rounded-full flex items-center justify-center text-white transition-colors"
            >
              <Maximize2 size={16} />
            </button>
          </div>

          {/* Center Play Button */}
          <div className="absolute inset-0 flex items-center justify-center">
            <button
              onClick={() => setPlaying(!isPlaying)}
              className={`w-16 h-16 bg-black/50 hover:bg-black/70 rounded-full flex items-center justify-center text-white transition-all ${
                isPlaying ? 'opacity-0 scale-75' : 'opacity-100 scale-100'
              }`}
            >
              {isPlaying ? <Pause size={24} /> : <Play size={24} />}
            </button>
          </div>

          {/* Bottom Controls */}
          <div className="absolute bottom-0 left-0 right-0 p-4">
            {/* Progress Bar */}
            <div className="mb-4">
              <input
                type="range"
                min="0"
                max={duration || 0}
                value={currentTime}
                onChange={handleSeek}
                className="w-full h-1 bg-white/30 rounded-lg appearance-none cursor-pointer slider"
                style={{
                  background: `linear-gradient(to right, #3b82f6 0%, #3b82f6 ${(currentTime / (duration || 1)) * 100}%, rgba(255,255,255,0.3) ${(currentTime / (duration || 1)) * 100}%, rgba(255,255,255,0.3) 100%)`
                }}
              />
            </div>

            {/* Control Buttons */}
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-4">
                <button
                  onClick={() => setPlaying(!isPlaying)}
                  className="text-white hover:text-primary-400 transition-colors"
                >
                  {isPlaying ? <Pause size={20} /> : <Play size={20} />}
                </button>

                <div className="flex items-center space-x-2">
                  <Volume2 className="text-white" size={16} />
                  <input
                    type="range"
                    min="0"
                    max="1"
                    step="0.01"
                    value={volume}
                    onChange={(e) => setVolume(parseFloat(e.target.value))}
                    className="w-20 h-1 bg-white/30 rounded-lg appearance-none cursor-pointer"
                  />
                </div>

                <span className="text-white text-sm">
                  {formatTime(currentTime)} / {formatTime(duration)}
                </span>
              </div>

              <div className="flex items-center space-x-2">
                <button
                  onClick={() => setCurrentTime(0)}
                  className="text-white hover:text-primary-400 transition-colors"
                  title="重置到开始"
                >
                  <RotateCcw size={16} />
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Processing Overlay */}
      {/* This would show when video is being processed */}
      <div className="absolute inset-0 bg-black/80 flex items-center justify-center" style={{ display: 'none' }}>
        <div className="text-center text-white">
          <div className="loading-spinner w-8 h-8 mx-auto mb-4"></div>
          <p>正在处理视频...</p>
        </div>
      </div>
    </div>
  )
}

export default VideoPreview
