import React, { useState, useCallback } from 'react';
import {
  Eye,
  Download,
  RefreshCw,
  AlertCircle,
  Clock,
  Monitor,
  Maximize2,
  X
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';

import { VideoFileInfo, FramePreviewRequest, FramePreviewResult } from '../../types/frame-extractor';

interface FramePreviewProps {
  video: VideoFileInfo;
  timestamp: number;
  onTimestampChange: (timestamp: number) => void;
  className?: string;
}

/**
 * 帧预览组件
 * 遵循 Tauri 开发规范和 UI/UX 设计标准
 */
export const FramePreview: React.FC<FramePreviewProps> = ({
  video,
  timestamp,
  onTimestampChange,
  className = ''
}) => {
  const [previewResult, setPreviewResult] = useState<FramePreviewResult | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [isFullscreen, setIsFullscreen] = useState(false);

  // 生成预览
  const generatePreview = useCallback(async () => {
    if (!video.is_valid) return;

    setIsLoading(true);
    try {
      const request: FramePreviewRequest = {
        video_path: video.path,
        timestamp: timestamp,
        output_size: {
          width: 640,
          height: 360,
          maintain_aspect_ratio: true,
          scale_filter: 'lanczos'
        }
      };

      const result = await invoke<FramePreviewResult>('preview_frame', { request });
      setPreviewResult(result);
    } catch (error) {
      console.error('生成预览失败:', error);
      setPreviewResult({
        success: false,
        preview_data: undefined,
        error_message: `预览失败: ${error}`,
        timestamp: timestamp,
        original_size: [video.width, video.height],
        preview_size: [0, 0]
      });
    } finally {
      setIsLoading(false);
    }
  }, [video, timestamp]);

  // 时间戳变化处理
  const handleTimestampChange = useCallback((newTimestamp: number) => {
    const clampedTimestamp = Math.max(0, Math.min(newTimestamp, video.duration));
    onTimestampChange(clampedTimestamp);
  }, [video.duration, onTimestampChange]);

  // 格式化时间
  const formatTime = (seconds: number): string => {
    const minutes = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    const ms = Math.floor((seconds % 1) * 1000);
    return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}.${ms.toString().padStart(3, '0')}`;
  };

  // 下载预览图片
  const downloadPreview = useCallback(() => {
    if (!previewResult?.preview_data) return;

    try {
      const link = document.createElement('a');
      link.href = `data:image/jpeg;base64,${previewResult.preview_data}`;
      link.download = `preview_${video.filename}_${formatTime(timestamp).replace(/:/g, '-')}.jpg`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (error) {
      console.error('下载预览图片失败:', error);
    }
  }, [previewResult, video.filename, timestamp]);

  return (
    <>
      <div className={`bg-white rounded-lg shadow-sm border p-4 space-y-4 ${className}`}>
        {/* 标题 */}
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Eye className="w-5 h-5 text-blue-600" />
            <h3 className="font-semibold text-gray-900">帧预览</h3>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={generatePreview}
              disabled={isLoading || !video.is_valid}
              className="px-3 py-1.5 bg-blue-500 text-white text-sm rounded-lg hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              {isLoading ? (
                <>
                  <RefreshCw className="w-3 h-3 inline mr-1 animate-spin" />
                  生成中...
                </>
              ) : (
                '生成预览'
              )}
            </button>
          </div>
        </div>

        {/* 时间轴控制 */}
        <div className="space-y-3">
          <div className="flex items-center justify-between text-sm">
            <span className="text-gray-600">时间位置</span>
            <span className="font-mono text-gray-900">{formatTime(timestamp)}</span>
          </div>
          
          <div className="relative">
            <input
              type="range"
              min="0"
              max={video.duration}
              step="0.1"
              value={timestamp}
              onChange={(e) => handleTimestampChange(parseFloat(e.target.value))}
              className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer slider"
            />
            <div className="flex justify-between text-xs text-gray-500 mt-1">
              <span>00:00</span>
              <span>{formatTime(video.duration)}</span>
            </div>
          </div>

          {/* 快速跳转按钮 */}
          <div className="flex items-center gap-2">
            <button
              onClick={() => handleTimestampChange(0)}
              className="px-2 py-1 text-xs bg-gray-100 text-gray-700 rounded hover:bg-gray-200 transition-colors"
            >
              开始
            </button>
            <button
              onClick={() => handleTimestampChange(video.duration * 0.25)}
              className="px-2 py-1 text-xs bg-gray-100 text-gray-700 rounded hover:bg-gray-200 transition-colors"
            >
              25%
            </button>
            <button
              onClick={() => handleTimestampChange(video.duration * 0.5)}
              className="px-2 py-1 text-xs bg-gray-100 text-gray-700 rounded hover:bg-gray-200 transition-colors"
            >
              50%
            </button>
            <button
              onClick={() => handleTimestampChange(video.duration * 0.75)}
              className="px-2 py-1 text-xs bg-gray-100 text-gray-700 rounded hover:bg-gray-200 transition-colors"
            >
              75%
            </button>
            <button
              onClick={() => handleTimestampChange(video.duration - 0.1)}
              className="px-2 py-1 text-xs bg-gray-100 text-gray-700 rounded hover:bg-gray-200 transition-colors"
            >
              结束
            </button>
          </div>
        </div>

        {/* 预览区域 */}
        <div className="space-y-3">
          {isLoading && (
            <div className="aspect-video bg-gray-100 rounded-lg flex items-center justify-center">
              <div className="text-center">
                <RefreshCw className="w-8 h-8 text-blue-500 animate-spin mx-auto mb-2" />
                <p className="text-sm text-gray-500">正在生成预览...</p>
              </div>
            </div>
          )}

          {!isLoading && previewResult && (
            <div className="space-y-3">
              {previewResult.success && previewResult.preview_data ? (
                <div className="relative group">
                  <img
                    src={`data:image/jpeg;base64,${previewResult.preview_data}`}
                    alt="Frame Preview"
                    className="w-full rounded-lg shadow-sm cursor-pointer hover:shadow-md transition-shadow"
                    onClick={() => setIsFullscreen(true)}
                  />
                  <div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-10 transition-all duration-200 rounded-lg flex items-center justify-center opacity-0 group-hover:opacity-100">
                    <Maximize2 className="w-8 h-8 text-white" />
                  </div>
                </div>
              ) : (
                <div className="aspect-video bg-red-50 border border-red-200 rounded-lg flex items-center justify-center">
                  <div className="text-center">
                    <AlertCircle className="w-8 h-8 text-red-500 mx-auto mb-2" />
                    <p className="text-sm text-red-600">
                      {previewResult.error_message || '预览生成失败'}
                    </p>
                  </div>
                </div>
              )}

              {/* 预览信息 */}
              {previewResult.success && (
                <div className="flex items-center justify-between text-xs text-gray-500">
                  <div className="flex items-center gap-4">
                    <div className="flex items-center gap-1">
                      <Monitor className="w-3 h-3" />
                      <span>
                        {previewResult.preview_size[0]}×{previewResult.preview_size[1]}
                      </span>
                    </div>
                    <div className="flex items-center gap-1">
                      <Clock className="w-3 h-3" />
                      <span>{formatTime(previewResult.timestamp)}</span>
                    </div>
                  </div>
                  
                  <button
                    onClick={downloadPreview}
                    className="flex items-center gap-1 px-2 py-1 bg-green-100 text-green-700 rounded hover:bg-green-200 transition-colors"
                  >
                    <Download className="w-3 h-3" />
                    <span>下载</span>
                  </button>
                </div>
              )}
            </div>
          )}

          {!isLoading && !previewResult && (
            <div className="aspect-video bg-gray-50 border-2 border-dashed border-gray-300 rounded-lg flex items-center justify-center">
              <div className="text-center">
                <Eye className="w-8 h-8 text-gray-400 mx-auto mb-2" />
                <p className="text-sm text-gray-500">点击"生成预览"查看帧内容</p>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* 全屏预览模态框 */}
      {isFullscreen && previewResult?.success && previewResult.preview_data && (
        <div className="fixed inset-0 bg-black bg-opacity-90 z-50 flex items-center justify-center p-4">
          <div className="relative max-w-full max-h-full">
            <button
              onClick={() => setIsFullscreen(false)}
              className="absolute -top-12 right-0 text-white hover:text-gray-300 transition-colors"
            >
              <X className="w-8 h-8" />
            </button>
            <img
              src={`data:image/jpeg;base64,${previewResult.preview_data}`}
              alt="Frame Preview Fullscreen"
              className="max-w-full max-h-full object-contain rounded-lg"
            />
            <div className="absolute bottom-0 left-0 right-0 bg-black bg-opacity-50 text-white p-4 rounded-b-lg">
              <div className="flex items-center justify-between text-sm">
                <span>{video.filename}</span>
                <span>{formatTime(previewResult.timestamp)}</span>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
};
