import React from 'react';
import {
  Video,
  Clock,
  Monitor,
  HardDrive,
  Trash2,
  AlertCircle,
  CheckCircle,
  RefreshCw,
  Eye
} from 'lucide-react';

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

interface VideoFileListProps {
  videos: VideoFileInfo[];
  isScanning: boolean;
  onRemoveVideo: (index: number) => void;
  onPreviewVideo?: (video: VideoFileInfo) => void;
}

/**
 * 视频文件列表组件
 * 遵循 Tauri 开发规范和 UI/UX 设计标准
 */
export const VideoFileList: React.FC<VideoFileListProps> = ({
  videos,
  isScanning,
  onRemoveVideo,
  onPreviewVideo
}) => {
  // 格式化文件大小
  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // 格式化时长
  const formatDuration = (seconds: number): string => {
    if (seconds === 0) return '00:00';
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = Math.floor(seconds % 60);
    
    if (hours > 0) {
      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    }
    return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  // 格式化分辨率
  const formatResolution = (width: number, height: number): string => {
    if (width === 0 || height === 0) return '未知';
    return `${width}×${height}`;
  };

  // 格式化帧率
  const formatFPS = (fps: number): string => {
    if (fps === 0) return '未知';
    return `${fps.toFixed(1)} fps`;
  };

  return (
    <div className="bg-white rounded-lg shadow-sm border">
      {/* 标题栏 */}
      <div className="flex items-center justify-between p-4 border-b">
        <div className="flex items-center gap-2">
          <Video className="w-5 h-5 text-blue-600" />
          <h3 className="font-semibold text-gray-900">视频文件列表</h3>
          {isScanning && (
            <RefreshCw className="w-4 h-4 text-blue-500 animate-spin" />
          )}
        </div>
        <div className="text-sm text-gray-500">
          {videos.length} 个文件
        </div>
      </div>

      {/* 文件列表 */}
      <div className="divide-y divide-gray-100 max-h-96 overflow-y-auto">
        {isScanning && videos.length === 0 && (
          <div className="p-8 text-center">
            <RefreshCw className="w-8 h-8 text-blue-500 animate-spin mx-auto mb-3" />
            <p className="text-gray-500">正在扫描视频文件...</p>
          </div>
        )}

        {!isScanning && videos.length === 0 && (
          <div className="p-8 text-center">
            <Video className="w-12 h-12 text-gray-300 mx-auto mb-3" />
            <p className="text-gray-500 mb-2">暂无视频文件</p>
            <p className="text-sm text-gray-400">请选择视频文件或文件夹</p>
          </div>
        )}

        {videos.map((video, index) => (
          <div key={`${video.path}-${index}`} className="p-4 hover:bg-gray-50 transition-colors">
            <div className="flex items-start justify-between gap-3">
              {/* 视频信息 */}
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 mb-2">
                  {video.is_valid ? (
                    <CheckCircle className="w-4 h-4 text-green-500 flex-shrink-0" />
                  ) : (
                    <AlertCircle className="w-4 h-4 text-red-500 flex-shrink-0" />
                  )}
                  <h4 className="font-medium text-gray-900 truncate" title={video.filename}>
                    {video.filename}
                  </h4>
                </div>

                {video.is_valid ? (
                  <div className="grid grid-cols-2 gap-2 text-xs text-gray-500">
                    <div className="flex items-center gap-1">
                      <Clock className="w-3 h-3" />
                      <span>{formatDuration(video.duration)}</span>
                    </div>
                    <div className="flex items-center gap-1">
                      <Monitor className="w-3 h-3" />
                      <span>{formatResolution(video.width, video.height)}</span>
                    </div>
                    <div className="flex items-center gap-1">
                      <HardDrive className="w-3 h-3" />
                      <span>{formatFileSize(video.size)}</span>
                    </div>
                    <div className="flex items-center gap-1">
                      <Video className="w-3 h-3" />
                      <span>{formatFPS(video.fps)}</span>
                    </div>
                  </div>
                ) : (
                  <div className="text-xs text-red-500">
                    {video.error_message || '无法读取视频信息'}
                  </div>
                )}

                <div className="mt-2 text-xs text-gray-400 truncate" title={video.path}>
                  {video.path}
                </div>
              </div>

              {/* 操作按钮 */}
              <div className="flex items-center gap-1 flex-shrink-0">
                {video.is_valid && onPreviewVideo && (
                  <button
                    onClick={() => onPreviewVideo(video)}
                    className="p-1.5 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded transition-colors"
                    title="预览"
                  >
                    <Eye className="w-4 h-4" />
                  </button>
                )}
                <button
                  onClick={() => onRemoveVideo(index)}
                  className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded transition-colors"
                  title="移除"
                >
                  <Trash2 className="w-4 h-4" />
                </button>
              </div>
            </div>

            {/* 视频格式和编码信息 */}
            {video.is_valid && video.format && (
              <div className="mt-2 flex items-center gap-2">
                <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                  {video.format.toUpperCase()}
                </span>
              </div>
            )}
          </div>
        ))}
      </div>

      {/* 统计信息 */}
      {videos.length > 0 && (
        <div className="p-4 border-t bg-gray-50">
          <div className="grid grid-cols-2 gap-4 text-sm">
            <div>
              <span className="text-gray-500">有效文件：</span>
              <span className="font-medium text-green-600 ml-1">
                {videos.filter(v => v.is_valid).length}
              </span>
            </div>
            <div>
              <span className="text-gray-500">无效文件：</span>
              <span className="font-medium text-red-600 ml-1">
                {videos.filter(v => !v.is_valid).length}
              </span>
            </div>
            <div>
              <span className="text-gray-500">总时长：</span>
              <span className="font-medium text-gray-900 ml-1">
                {formatDuration(videos.reduce((total, v) => total + (v.is_valid ? v.duration : 0), 0))}
              </span>
            </div>
            <div>
              <span className="text-gray-500">总大小：</span>
              <span className="font-medium text-gray-900 ml-1">
                {formatFileSize(videos.reduce((total, v) => total + v.size, 0))}
              </span>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
