import React, { useState, useRef, useEffect, useImperativeHandle, forwardRef } from 'react'
import { Play, Pause, Volume2, VolumeX, Maximize2, X, AlertCircle, Loader2 } from 'lucide-react'
import { convertFileSrc, invoke } from '@tauri-apps/api/core'

// 接口定义
export interface OnSourceLoaded {
  (player: HTMLVideoElement | null): void;
}

export interface OnPlayerError {
  (err: Error, player: HTMLVideoElement | null): void;
}

export interface OnPlayerTimeChange {
  (player: HTMLVideoElement | null): void;
}

export interface VideoPlayerRef {
  seek(time: number): void;
  pause(): void;
  play(): void;
  getCurrentTime(): number;
  isPaused(): boolean;
  getDuration(): number;
  captureFrame(): string | undefined;
  fullScreen(): void;
  reload(): void;
}

interface VideoPlayerProps {
  videoPath: string
  isOpen: boolean
  onClose: () => void
  title?: string
  onSourceLoaded?: OnSourceLoaded
  onError?: OnPlayerError
  onTimeChange?: OnPlayerTimeChange
}

const VideoPlayer = forwardRef<VideoPlayerRef, VideoPlayerProps>(({
  videoPath,
  isOpen,
  onClose,
  title = '视频播放',
  onSourceLoaded,
  onError,
  onTimeChange
}, ref) => {
  const videoRef = useRef<HTMLVideoElement>(null)
  const [isPlaying, setIsPlaying] = useState(false)
  const [isMuted, setIsMuted] = useState(false)
  const [currentTime, setCurrentTime] = useState(0)
  const [duration, setDuration] = useState(0)
  const [volume, setVolume] = useState(1)
  const [isFullscreen, setIsFullscreen] = useState(false)
  const [videoSrc, setVideoSrc] = useState<string>('')
  const [fileExists, setFileExists] = useState<boolean>(true)
  const [errorMessage, setErrorMessage] = useState<string>('')
  const [loadingMethod, setLoadingMethod] = useState<'convertFileSrc' | 'dataUrl'>('convertFileSrc')
  const [isLoading, setIsLoading] = useState(true)

  // 暴露组件方法
  useImperativeHandle(ref, () => ({
    seek: (time: number) => {
      const video = videoRef.current
      if (video) {
        video.currentTime = time
        setCurrentTime(time)
      }
    },
    pause: () => {
      videoRef.current?.pause()
    },
    play: () => {
      videoRef.current?.play().catch(err => {
        console.error('Play failed:', err)
        onError?.(new Error('播放失败'), videoRef.current)
      })
    },
    isPaused: () => {
      return !!videoRef.current?.paused
    },
    getCurrentTime: () => {
      return videoRef.current?.currentTime || 0
    },
    getDuration: () => {
      return videoRef.current?.duration || 0
    },
    captureFrame: () => {
      const video = videoRef.current
      if (!video) return undefined

      // 创建canvas元素
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      if (!ctx) return undefined

      // 设置canvas尺寸
      canvas.width = video.videoWidth
      canvas.height = video.videoHeight

      // 绘制视频帧到canvas
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
      const dataURL = canvas.toDataURL('image/jpeg', 0.8)
      return dataURL
    },
    fullScreen: () => {
      const video = videoRef.current
      if (video) {
        video.requestFullscreen().catch(err => {
          console.error('Fullscreen failed:', err)
        })
      }
    },
    reload: () => {
      if (videoPath) {
        tryLoadVideo(videoPath)
      }
    }
  }))

  // 加载状态管理
  useEffect(() => {
    const video = videoRef.current
    if (!video) return

    const showLoading = () => setIsLoading(true)
    const hideLoading = () => setIsLoading(false)

    // 加载状态事件
    video.addEventListener('waiting', showLoading)
    video.addEventListener('seeking', showLoading)
    video.addEventListener('loadstart', showLoading)

    video.addEventListener('playing', hideLoading)
    video.addEventListener('seeked', hideLoading)
    video.addEventListener('canplay', hideLoading)
    video.addEventListener('loadeddata', hideLoading)

    return () => {
      video.removeEventListener('waiting', showLoading)
      video.removeEventListener('seeking', showLoading)
      video.removeEventListener('loadstart', showLoading)
      video.removeEventListener('playing', hideLoading)
      video.removeEventListener('seeked', hideLoading)
      video.removeEventListener('canplay', hideLoading)
      video.removeEventListener('loadeddata', hideLoading)
    }
  }, [])

  // 视频源加载和事件处理
  useEffect(() => {
    const checkFileAndSetSrc = async () => {
      if (isOpen && videoPath) {
        try {
          // 首先检查文件是否存在
          const exists = await invoke<boolean>('check_file_exists', { filePath: videoPath })
          console.log('File exists check:', { videoPath, exists })

          if (!exists) {
            setFileExists(false)
            setErrorMessage(`文件不存在: ${videoPath}`)
            onError?.(new Error(`文件不存在: ${videoPath}`), videoRef.current)
            return
          }

          setFileExists(true)
          setErrorMessage('')

          // 尝试多种方法加载视频
          await tryLoadVideo(videoPath)
        } catch (error) {
          console.error('Error checking file:', error)
          setFileExists(false)
          const errorMsg = `文件检查失败: ${error}`
          setErrorMessage(errorMsg)
          onError?.(new Error(errorMsg), videoRef.current)
        }
      }
    }

    checkFileAndSetSrc()
  }, [isOpen, videoPath, onError])

  // 尝试多种方法加载视频
  const tryLoadVideo = async (path: string) => {
    try {
      // 首先尝试convertFileSrc方法
      const src = convertFileSrc(path)
      console.log(`try load video src`, src)
      setVideoSrc(src)
      setLoadingMethod('convertFileSrc')
      return
    } catch (error) {
      console.error('convertFileSrc failed:', error)

      // 如果失败，尝试data URL方法
      try {
        console.log('Trying data URL method for:', path)
        const dataUrl = await invoke<string>('read_video_as_data_url', { filePath: path })
        console.log('Data URL method successful, length:', dataUrl.length)
        setVideoSrc(dataUrl)
        setLoadingMethod('dataUrl')
        return
      } catch (dataUrlError) {
        console.error('Data URL method failed:', dataUrlError)
        setErrorMessage('无法加载视频：所有加载方法都失败了')
      }
    }
  }

  // 视频播放事件处理
  useEffect(() => {
    const video = videoRef.current
    if (!video) return

    const handleTimeUpdate = () => {
      setCurrentTime(video.currentTime)
      onTimeChange?.(video)
    }

    const handleDurationChange = () => {
      setDuration(video.duration)
    }

    const handleEnded = () => {
      setIsPlaying(false)
    }

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

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

    const handleLoadedMetadata = () => {
      console.log('Video metadata loaded:', {
        duration: video.duration,
        videoWidth: video.videoWidth,
        videoHeight: video.videoHeight
      })
      onSourceLoaded?.(video)
    }

    const handleError = (e: Event) => {
      console.error('Video error:', e)
      const error = new Error('视频播放错误')
      setErrorMessage('视频播放错误')
      onError?.(error, video)
    }

    // 添加事件监听器
    video.addEventListener('timeupdate', handleTimeUpdate)
    video.addEventListener('durationchange', handleDurationChange)
    video.addEventListener('ended', handleEnded)
    video.addEventListener('play', handlePlay)
    video.addEventListener('pause', handlePause)
    video.addEventListener('loadedmetadata', handleLoadedMetadata)
    video.addEventListener('error', handleError)

    return () => {
      video.removeEventListener('timeupdate', handleTimeUpdate)
      video.removeEventListener('durationchange', handleDurationChange)
      video.removeEventListener('ended', handleEnded)
      video.removeEventListener('play', handlePlay)
      video.removeEventListener('pause', handlePause)
      video.removeEventListener('loadedmetadata', handleLoadedMetadata)
      video.removeEventListener('error', handleError)
    }
  }, [onTimeChange, onSourceLoaded, onError])

  // 视频源设置和清理
  useEffect(() => {
    const video = videoRef.current
    if (!video || !videoSrc) return

    // 设置视频源
    video.src = videoSrc
    video.load()

    console.log('Video src set to:', videoSrc)

    // 清理函数
    return () => {
      if (video) {
        video.src = ''
        video.load()
      }
    }
  }, [videoSrc])

  const handlePlayPause = () => {
    const video = videoRef.current
    if (!video) return

    if (isPlaying) {
      video.pause()
    } else {
      video.play().catch(err => {
        console.error('Failed to play video:', err)
      })
    }
  }

  const handleSeek = (e: React.ChangeEvent<HTMLInputElement>) => {
    const video = videoRef.current
    if (!video) return

    const newTime = parseFloat(e.target.value)
    video.currentTime = newTime
    setCurrentTime(newTime)
  }

  const handleVolumeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const video = videoRef.current
    if (!video) return

    const newVolume = parseFloat(e.target.value)
    video.volume = newVolume
    setVolume(newVolume)
    setIsMuted(newVolume === 0)
  }

  const handleMuteToggle = () => {
    const video = videoRef.current
    if (!video) return

    if (isMuted) {
      video.volume = volume
      setIsMuted(false)
    } else {
      video.volume = 0
      setIsMuted(true)
    }
  }

  const handleFullscreen = () => {
    const video = videoRef.current
    if (!video) return

    if (!isFullscreen) {
      if (video.requestFullscreen) {
        video.requestFullscreen()
        setIsFullscreen(true)
      }
    } else {
      if (document.exitFullscreen) {
        document.exitFullscreen()
        setIsFullscreen(false)
      }
    }
  }

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

  if (!isOpen) return null

  return (
    <div className="fixed inset-0 bg-black bg-opacity-90 flex items-center justify-center z-50">
      <div className="relative w-full max-w-4xl mx-4">
        {/* 关闭按钮 */}
        <button
          onClick={onClose}
          className="absolute top-4 right-4 z-10 p-2 bg-black/50 text-white rounded-full hover:bg-black/70 transition-colors"
        >
          <X size={24} />
        </button>

        {/* 标题 */}
        <div className="absolute top-4 left-4 z-10 text-white">
          <h3 className="text-lg font-medium">{title}</h3>
        </div>

        {/* 视频容器 */}
        <div className="relative bg-black rounded-lg overflow-hidden">
          {!fileExists || errorMessage ? (
            /* 错误显示 */
            <div className="flex items-center justify-center h-96 text-white">
              <div className="text-center">
                <AlertCircle size={64} className="mx-auto mb-4 text-red-400" />
                <h3 className="text-xl font-medium mb-2">视频加载失败</h3>
                <p className="text-gray-300 mb-4">{errorMessage}</p>
                <p className="text-sm text-gray-400 mb-4">文件路径: {videoPath}</p>
                <p className="text-xs text-gray-500 mb-4">当前加载方法: {loadingMethod}</p>
                {loadingMethod === 'convertFileSrc' && (
                  <button
                    onClick={() => {
                      if (videoPath) {
                        tryLoadVideo(videoPath).catch(err => {
                          console.error('Manual reload failed:', err)
                          setErrorMessage('备用加载方法也失败了')
                        })
                      }
                    }}
                    className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                  >
                    尝试备用加载方法
                  </button>
                )}
              </div>
            </div>
          ) : (
            <div className="relative w-full">
              <video
                ref={videoRef}
                className="w-full h-auto max-h-[70vh] bg-black"
                onClick={handlePlayPause}
                crossOrigin="anonymous"
                preload="auto"
              />

              {/* 加载状态显示 */}
              {isLoading && (
                <div className="absolute inset-0 flex items-center justify-center bg-black/50">
                  <div className="flex flex-col items-center space-y-2">
                    <Loader2 className="h-8 w-8 animate-spin text-white" />
                    <span className="text-white text-sm">加载中...</span>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* 控制栏 */}
          <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-4">
            {/* 进度条 */}
            <div className="mb-4">
              <input
                type="range"
                min="0"
                max={duration || 0}
                value={currentTime}
                onChange={handleSeek}
                className="w-full h-1 bg-gray-600 rounded-lg appearance-none cursor-pointer slider"
              />
            </div>

            {/* 控制按钮 */}
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-4">
                {/* 播放/暂停 */}
                <button
                  onClick={handlePlayPause}
                  className="p-2 text-white hover:text-blue-400 transition-colors"
                >
                  {isPlaying ? <Pause size={24} /> : <Play size={24} />}
                </button>

                {/* 音量控制 */}
                <div className="flex items-center space-x-2">
                  <button
                    onClick={handleMuteToggle}
                    className="text-white hover:text-blue-400 transition-colors"
                  >
                    {isMuted ? <VolumeX size={20} /> : <Volume2 size={20} />}
                  </button>
                  <input
                    type="range"
                    min="0"
                    max="1"
                    step="0.1"
                    value={isMuted ? 0 : volume}
                    onChange={handleVolumeChange}
                    className="w-20 h-1 bg-gray-600 rounded-lg appearance-none cursor-pointer"
                  />
                </div>

                {/* 时间显示 */}
                <div className="text-white text-sm">
                  {formatTime(currentTime)} / {formatTime(duration)}
                </div>
              </div>

              <div className="flex items-center space-x-2">
                {/* 全屏按钮 */}
                <button
                  onClick={handleFullscreen}
                  className="p-2 text-white hover:text-blue-400 transition-colors"
                >
                  <Maximize2 size={20} />
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
})

VideoPlayer.displayName = 'VideoPlayer'

export default VideoPlayer
