import React, { useState, useCallback, useRef, useEffect } from 'react';
import { Modal } from './Modal';
import {
  Play,
  Pause,
  Volume2,
  VolumeX,
  Download,
  ExternalLink,
  Maximize,
  SkipBack,
  SkipForward
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
import { useNotifications } from './NotificationSystem';

/**
 * 视频预览模态框属性接口
 */
interface VideoPreviewModalProps {
  /** 是否显示模态框 */
  isOpen: boolean;
  /** 视频URL */
  videoUrl: string | null;
  /** 视频标题 */
  title?: string;
  /** 关闭回调 */
  onClose: () => void;
  /** 下载回调 */
  onDownload?: (videoUrl: string) => void;
}

/**
 * 视频预览模态框组件
 * 支持视频播放控制、全屏、下载等功能
 */
export const VideoPreviewModal: React.FC<VideoPreviewModalProps> = ({
  isOpen,
  videoUrl,
  title = '视频预览',
  onClose,
  onDownload
}) => {
  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 [isFullscreen, setIsFullscreen] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isDownloading, setIsDownloading] = useState(false);
  const [proxiedVideoUrl, setProxiedVideoUrl] = useState<string | null>(null);
  const [isLoadingProxy, setIsLoadingProxy] = useState(false);
  
  const { addNotification } = useNotifications();

  // 加载代理视频
  useEffect(() => {
    if (!videoUrl || !isOpen) return;

    // 重置状态
    setError(null);
    setIsLoading(true);
    setIsLoadingProxy(false);

    // 首先尝试直接加载
    setProxiedVideoUrl(videoUrl);
  }, [videoUrl, isOpen]);

  // 重置状态当视频URL改变时
  useEffect(() => {
    if (videoUrl) {
      setIsLoading(true);
      setError(null);
      setIsPlaying(false);
      setCurrentTime(0);
      setDuration(0);
    }
  }, [videoUrl]);

  // 播放/暂停控制
  const handlePlayPause = useCallback(() => {
    if (!videoRef.current) return;
    
    if (isPlaying) {
      videoRef.current.pause();
    } else {
      videoRef.current.play().catch(err => {
        console.error('播放失败:', err);
        setError('视频播放失败');
      });
    }
  }, [isPlaying]);

  // 静音控制
  const handleMuteToggle = useCallback(() => {
    if (!videoRef.current) return;
    
    const newMuted = !isMuted;
    videoRef.current.muted = newMuted;
    setIsMuted(newMuted);
  }, [isMuted]);

  // 进度控制
  const handleSeek = useCallback((newTime: number) => {
    if (!videoRef.current) return;
    
    videoRef.current.currentTime = newTime;
    setCurrentTime(newTime);
  }, []);

  // 快进/快退
  const handleSkip = useCallback((seconds: number) => {
    if (!videoRef.current) return;
    
    const newTime = Math.max(0, Math.min(duration, currentTime + seconds));
    handleSeek(newTime);
  }, [currentTime, duration, handleSeek]);

  // 全屏控制
  const handleFullscreen = useCallback(() => {
    if (!videoRef.current) return;
    
    if (!isFullscreen) {
      if (videoRef.current.requestFullscreen) {
        videoRef.current.requestFullscreen();
      }
    } else {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      }
    }
  }, [isFullscreen]);

  // 下载视频
  const handleDownload = useCallback(async () => {
    if (!videoUrl) return;
    
    setIsDownloading(true);
    try {
      // 调用Tauri命令下载视频
      await invoke('download_video_to_directory', {
        videoUrl,
        filename: `video_${Date.now()}.mp4`
      });
      
      addNotification({
        type: 'success',
        title: '下载成功',
        message: '视频下载成功'
      });
      
      if (onDownload) {
        onDownload(videoUrl);
      }
    } catch (error) {
      console.error('下载失败:', error);
      addNotification({
        type: 'error',
        title: '下载失败',
        message: `视频下载失败: ${error}`
      });
    } finally {
      setIsDownloading(false);
    }
  }, [videoUrl, onDownload, addNotification]);

  // 在新窗口打开
  const handleOpenInNewWindow = useCallback(() => {
    if (videoUrl) {
      window.open(videoUrl, '_blank');
    }
  }, [videoUrl]);

  // 视频事件处理
  const handleVideoLoad = useCallback(() => {
    setIsLoading(false);
    if (videoRef.current) {
      setDuration(videoRef.current.duration);
    }
  }, []);

  const handleVideoError = useCallback(async () => {
    console.log('视频加载失败，尝试使用代理服务');

    // 如果还没有尝试过代理，则尝试使用代理服务
    if (proxiedVideoUrl === videoUrl) {
      try {
        setIsLoading(false); // 停止普通加载状态
        setIsLoadingProxy(true); // 开始代理加载状态
        setError(null);

        console.log('开始获取代理视频数据...');
        const proxiedData = await invoke<string>('get_video_stream_base64', {
          videoUrl: videoUrl
        });

        setProxiedVideoUrl(proxiedData);
        console.log('成功获取代理视频数据，大小:', proxiedData.length);
      } catch (error) {
        console.error('代理视频加载失败:', error);
        setError('视频加载失败，请检查网络连接或视频链接');
      } finally {
        setIsLoadingProxy(false);
      }
    } else {
      setIsLoading(false);
      setError('视频加载失败，请检查网络连接或视频链接');
    }
  }, [videoUrl, proxiedVideoUrl]);

  const handleTimeUpdate = useCallback(() => {
    if (videoRef.current) {
      setCurrentTime(videoRef.current.currentTime);
    }
  }, []);

  const handlePlay = useCallback(() => {
    setIsPlaying(true);
  }, []);

  const handlePause = useCallback(() => {
    setIsPlaying(false);
  }, []);

  const handleFullscreenChange = useCallback(() => {
    setIsFullscreen(!!document.fullscreenElement);
  }, []);

  // 监听全屏变化
  useEffect(() => {
    document.addEventListener('fullscreenchange', handleFullscreenChange);
    return () => {
      document.removeEventListener('fullscreenchange', handleFullscreenChange);
    };
  }, [handleFullscreenChange]);

  // 格式化时间
  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 || !videoUrl) {
    return null;
  }

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title={title}
      size="xl"
      className="video-preview-modal"
    >
      <div className="space-y-4">
        {/* 视频播放区域 */}
        <div className="relative bg-black rounded-lg overflow-hidden aspect-video group">
          {(isLoading || isLoadingProxy) && (
            <div className="absolute inset-0 flex items-center justify-center bg-gray-900">
              <div className="flex flex-col items-center space-y-3">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
                <p className="text-white text-sm">
                  {isLoadingProxy ? '正在获取视频流...' : '加载中...'}
                </p>
              </div>
            </div>
          )}

          {error && (
            <div className="absolute inset-0 flex items-center justify-center bg-gray-900 text-white">
              <div className="text-center">
                <div className="text-red-400 mb-2">⚠️</div>
                <p>{error}</p>
              </div>
            </div>
          )}

          <video
            ref={videoRef}
            className="w-full h-full object-contain"
            onLoadedData={handleVideoLoad}
            onError={handleVideoError}
            onTimeUpdate={handleTimeUpdate}
            onPlay={handlePlay}
            onPause={handlePause}
            controls={false}
            crossOrigin="anonymous"
          >
            {proxiedVideoUrl && (
              <source src={proxiedVideoUrl} type="video/mp4" />
            )}
            您的浏览器不支持视频播放。
          </video>

          {/* 右上角悬浮按钮组 */}
          {!isLoading && !isLoadingProxy && !error && (
            <div className="absolute top-4 right-4 flex items-center space-x-2 opacity-80 hover:opacity-100 group-hover:opacity-100 transition-all duration-300 z-10">
              <button
                onClick={handleDownload}
                disabled={isDownloading}
                className="relative flex items-center justify-center w-10 h-10 bg-black/60 hover:bg-green-600/80 disabled:bg-gray-600/60 text-white rounded-full backdrop-blur-sm transition-all duration-200 hover:scale-110 disabled:cursor-not-allowed shadow-lg"
                title={isDownloading ? '下载中...' : '下载视频'}
              >
                {isDownloading ? (
                  <div className="animate-spin rounded-full h-5 w-5 border-2 border-white border-t-transparent"></div>
                ) : (
                  <Download className="w-5 h-5" />
                )}
              </button>

              <button
                onClick={handleOpenInNewWindow}
                className="flex items-center justify-center w-10 h-10 bg-black/60 hover:bg-blue-600/80 text-white rounded-full backdrop-blur-sm transition-all duration-200 hover:scale-110 shadow-lg"
                title="在新窗口打开"
              >
                <ExternalLink className="w-5 h-5" />
              </button>

              <button
                onClick={handleFullscreen}
                className="flex items-center justify-center w-10 h-10 bg-black/60 hover:bg-purple-600/80 text-white rounded-full backdrop-blur-sm transition-all duration-200 hover:scale-110 shadow-lg"
                title="全屏播放"
              >
                <Maximize className="w-5 h-5" />
              </button>
            </div>
          )}
          
          {/* 视频控制覆盖层 */}
          {!isLoading && !error && (
            <div className="absolute inset-0 bg-gradient-to-t from-black/50 via-transparent to-transparent opacity-0 hover:opacity-100 transition-opacity duration-300">
              {/* 中央播放按钮 */}
              <div className="absolute inset-0 flex items-center justify-center">
                <button
                  onClick={handlePlayPause}
                  className="bg-white/20 hover:bg-white/30 rounded-full p-4 transition-colors duration-200"
                >
                  {isPlaying ? (
                    <Pause className="w-8 h-8 text-white" />
                  ) : (
                    <Play className="w-8 h-8 text-white ml-1" />
                  )}
                </button>
              </div>
              
              {/* 底部控制栏 */}
              <div className="absolute bottom-0 left-0 right-0 p-4">
                <div className="space-y-2">
                  {/* 进度条 */}
                  <div className="flex items-center space-x-2 text-white text-sm">
                    <span>{formatTime(currentTime)}</span>
                    <div className="flex-1 bg-white/20 rounded-full h-1">
                      <div
                        className="bg-blue-500 h-1 rounded-full transition-all duration-100"
                        style={{ width: `${duration > 0 ? (currentTime / duration) * 100 : 0}%` }}
                      />
                    </div>
                    <span>{formatTime(duration)}</span>
                  </div>
                  
                  {/* 控制按钮 */}
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-2">
                      <button
                        onClick={() => handleSkip(-10)}
                        className="text-white hover:text-blue-400 transition-colors duration-200"
                        title="后退10秒"
                      >
                        <SkipBack className="w-5 h-5" />
                      </button>
                      
                      <button
                        onClick={handlePlayPause}
                        className="text-white hover:text-blue-400 transition-colors duration-200"
                      >
                        {isPlaying ? <Pause className="w-5 h-5" /> : <Play className="w-5 h-5" />}
                      </button>
                      
                      <button
                        onClick={() => handleSkip(10)}
                        className="text-white hover:text-blue-400 transition-colors duration-200"
                        title="前进10秒"
                      >
                        <SkipForward className="w-5 h-5" />
                      </button>
                      
                      <button
                        onClick={handleMuteToggle}
                        className="text-white hover:text-blue-400 transition-colors duration-200"
                      >
                        {isMuted ? <VolumeX className="w-5 h-5" /> : <Volume2 className="w-5 h-5" />}
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </Modal>
  );
};

export default VideoPreviewModal;
