import React, { useState } from 'react';
import {
  CheckCircle,
  AlertCircle,
  ExternalLink,
  Download,
  Eye,
  Clock,
  HardDrive,
  Image,
  Filter,
  Grid,
  List,
  Search
} from 'lucide-react';

import { FrameExtractionResult, FrameType } from '../../types/frame-extractor';

interface ExtractionResultsProps {
  results: FrameExtractionResult[];
  onOpenResult: (result: FrameExtractionResult) => void;
  onPreviewResult?: (result: FrameExtractionResult) => void;
  onDownloadResult?: (result: FrameExtractionResult) => void;
}

/**
 * 关键帧提取结果展示组件
 * 遵循 Tauri 开发规范和 UI/UX 设计标准
 */
export const ExtractionResults: React.FC<ExtractionResultsProps> = ({
  results,
  onOpenResult,
  onPreviewResult,
  onDownloadResult
}) => {
  const [filter, setFilter] = useState<'all' | 'success' | 'failed'>('all');
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('list');
  const [searchQuery, setSearchQuery] = useState('');

  // 过滤结果
  const filteredResults = results.filter(result => {
    // 状态过滤
    if (filter === 'success' && !result.success) return false;
    if (filter === 'failed' && result.success) return false;
    
    // 搜索过滤
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      const videoName = result.video_path.toLowerCase();
      const outputName = result.output_path.toLowerCase();
      if (!videoName.includes(query) && !outputName.includes(query)) {
        return false;
      }
    }
    
    return true;
  });

  // 统计信息
  const stats = {
    total: results.length,
    success: results.filter(r => r.success).length,
    failed: results.filter(r => !r.success).length,
    totalSize: results.reduce((sum, r) => sum + (r.success ? r.file_size : 0), 0),
    totalTime: results.reduce((sum, r) => sum + r.processing_time_ms, 0)
  };

  // 格式化文件大小
  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 formatProcessingTime = (ms: number): string => {
    if (ms < 1000) return `${ms}ms`;
    const seconds = ms / 1000;
    if (seconds < 60) return `${seconds.toFixed(1)}s`;
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = Math.round(seconds % 60);
    return `${minutes}m ${remainingSeconds}s`;
  };

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

  // 获取帧类型显示名称
  const getFrameTypeName = (frameType: FrameType): string => {
    switch (frameType) {
      case FrameType.First: return '第一帧';
      case FrameType.Last: return '最后一帧';
      case FrameType.Custom: return '自定义';
      case FrameType.Multiple: return '多帧';
      default: return '未知';
    }
  };

  return (
    <div className="bg-white rounded-lg shadow-sm border space-y-6">
      {/* 标题和统计 */}
      <div className="p-6 border-b">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-semibold text-gray-900">提取结果</h3>
          <div className="flex items-center gap-2">
            <button
              onClick={() => setViewMode('list')}
              className={`p-2 rounded-lg transition-colors ${
                viewMode === 'list'
                  ? 'bg-blue-100 text-blue-600'
                  : 'text-gray-400 hover:text-gray-600'
              }`}
            >
              <List className="w-4 h-4" />
            </button>
            <button
              onClick={() => setViewMode('grid')}
              className={`p-2 rounded-lg transition-colors ${
                viewMode === 'grid'
                  ? 'bg-blue-100 text-blue-600'
                  : 'text-gray-400 hover:text-gray-600'
              }`}
            >
              <Grid className="w-4 h-4" />
            </button>
          </div>
        </div>

        {/* 统计卡片 */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
          <div className="text-center p-3 bg-gray-50 rounded-lg">
            <div className="text-2xl font-bold text-gray-900">{stats.total}</div>
            <div className="text-xs text-gray-500">总数</div>
          </div>
          <div className="text-center p-3 bg-green-50 rounded-lg">
            <div className="text-2xl font-bold text-green-600">{stats.success}</div>
            <div className="text-xs text-gray-500">成功</div>
          </div>
          <div className="text-center p-3 bg-red-50 rounded-lg">
            <div className="text-2xl font-bold text-red-600">{stats.failed}</div>
            <div className="text-xs text-gray-500">失败</div>
          </div>
          <div className="text-center p-3 bg-blue-50 rounded-lg">
            <div className="text-2xl font-bold text-blue-600">{formatFileSize(stats.totalSize)}</div>
            <div className="text-xs text-gray-500">总大小</div>
          </div>
        </div>

        {/* 过滤和搜索 */}
        <div className="flex flex-col sm:flex-row gap-3">
          <div className="flex items-center gap-2">
            <Filter className="w-4 h-4 text-gray-400" />
            <select
              value={filter}
              onChange={(e) => setFilter(e.target.value as any)}
              className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            >
              <option value="all">全部结果</option>
              <option value="success">仅成功</option>
              <option value="failed">仅失败</option>
            </select>
          </div>
          
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="搜索文件名..."
              className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>
        </div>
      </div>

      {/* 结果列表 */}
      <div className="px-6 pb-6">
        {filteredResults.length === 0 ? (
          <div className="text-center py-12">
            <Image className="w-12 h-12 text-gray-300 mx-auto mb-3" />
            <p className="text-gray-500 mb-2">
              {results.length === 0 ? '暂无提取结果' : '没有符合条件的结果'}
            </p>
            {results.length === 0 && (
              <p className="text-sm text-gray-400">请先开始提取操作</p>
            )}
          </div>
        ) : (
          <div className={viewMode === 'grid' ? 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4' : 'space-y-3'}>
            {filteredResults.map((result, index) => (
              <div
                key={`${result.video_path}-${result.timestamp}-${index}`}
                className={`border rounded-lg p-4 hover:shadow-md transition-shadow ${
                  result.success ? 'border-green-200 bg-green-50' : 'border-red-200 bg-red-50'
                }`}
              >
                <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">
                      {result.success ? (
                        <CheckCircle className="w-4 h-4 text-green-600 flex-shrink-0" />
                      ) : (
                        <AlertCircle className="w-4 h-4 text-red-600 flex-shrink-0" />
                      )}
                      <span className="font-medium text-gray-900 truncate">
                        {result.video_path.split('/').pop() || result.video_path}
                      </span>
                    </div>

                    {/* 详细信息 */}
                    <div className="space-y-1 text-xs text-gray-600">
                      <div className="flex items-center gap-4">
                        <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                          {getFrameTypeName(result.frame_type)}
                        </span>
                        <div className="flex items-center gap-1">
                          <Clock className="w-3 h-3" />
                          <span>{formatTimestamp(result.timestamp)}</span>
                        </div>
                      </div>
                      
                      {result.success && (
                        <div className="flex items-center gap-4">
                          <div className="flex items-center gap-1">
                            <HardDrive className="w-3 h-3" />
                            <span>{formatFileSize(result.file_size)}</span>
                          </div>
                          <div className="flex items-center gap-1">
                            <Clock className="w-3 h-3" />
                            <span>{formatProcessingTime(result.processing_time_ms)}</span>
                          </div>
                        </div>
                      )}
                      
                      {result.error_message && (
                        <div className="text-red-600 text-xs mt-1">
                          {result.error_message}
                        </div>
                      )}
                    </div>

                    {/* 输出路径 */}
                    {result.success && (
                      <div className="mt-2 text-xs text-gray-500 truncate" title={result.output_path}>
                        {result.output_path}
                      </div>
                    )}
                  </div>

                  {/* 操作按钮 */}
                  {result.success && (
                    <div className="flex items-center gap-1 flex-shrink-0">
                      {onPreviewResult && (
                        <button
                          onClick={() => onPreviewResult(result)}
                          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>
                      )}
                      {onDownloadResult && (
                        <button
                          onClick={() => onDownloadResult(result)}
                          className="p-1.5 text-gray-400 hover:text-green-600 hover:bg-green-50 rounded transition-colors"
                          title="下载"
                        >
                          <Download className="w-4 h-4" />
                        </button>
                      )}
                      <button
                        onClick={() => onOpenResult(result)}
                        className="p-1.5 text-gray-400 hover:text-purple-600 hover:bg-purple-50 rounded transition-colors"
                        title="打开文件位置"
                      >
                        <ExternalLink className="w-4 h-4" />
                      </button>
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};
