import React, { useState, useEffect } from 'react';
import { 
  Download, 
  Eye, 
  Play, 
  Pause, 
  Volume2, 
  VolumeX,
  Image as ImageIcon,
  Video,
  Music,
  FileText,
  ExternalLink,
  Grid,
  List,
  Maximize2,
  X
} from 'lucide-react';

interface WorkflowResult {
  id: string;
  type: 'image' | 'video' | 'audio' | 'text' | 'file' | 'json';
  url?: string;
  content?: string;
  metadata?: {
    filename?: string;
    size?: number;
    duration?: number;
    dimensions?: { width: number; height: number };
    format?: string;
  };
}

interface WorkflowResultDisplayProps {
  /** 执行结果数据 */
  results: WorkflowResult[];
  /** 输出schema配置 */
  outputSchema?: any;
  /** 是否显示下载按钮 */
  showDownload?: boolean;
  /** 是否显示全屏按钮 */
  showFullscreen?: boolean;
  /** 布局模式 */
  layout?: 'grid' | 'list';
  /** 结果点击回调 */
  onResultClick?: (result: WorkflowResult) => void;
}

export const WorkflowResultDisplay: React.FC<WorkflowResultDisplayProps> = ({
  results,
  outputSchema,
  showDownload = true,
  showFullscreen = true,
  layout = 'grid',
  onResultClick
}) => {
  const [currentLayout, setCurrentLayout] = useState(layout);
  const [selectedResult, setSelectedResult] = useState<WorkflowResult | null>(null);
  const [isFullscreen, setIsFullscreen] = useState(false);

  // 根据类型获取图标
  const getTypeIcon = (type: string) => {
    switch (type) {
      case 'image':
        return <ImageIcon className="w-4 h-4" />;
      case 'video':
        return <Video className="w-4 h-4" />;
      case 'audio':
        return <Music className="w-4 h-4" />;
      case 'text':
        return <FileText className="w-4 h-4" />;
      default:
        return <FileText className="w-4 h-4" />;
    }
  };

  // 格式化文件大小
  const formatFileSize = (bytes?: number) => {
    if (!bytes) return '';
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return `${(bytes / Math.pow(1024, i)).toFixed(1)} ${sizes[i]}`;
  };

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

  // 下载文件
  const downloadFile = (result: WorkflowResult) => {
    if (!result.url) return;
    
    const link = document.createElement('a');
    link.href = result.url;
    link.download = result.metadata?.filename || `result.${result.type}`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  // 渲染单个结果
  const renderResult = (result: WorkflowResult, index: number) => {
    const isSelected = selectedResult?.id === result.id;
    
    return (
      <div
        key={result.id}
        className={`border rounded-lg overflow-hidden transition-all cursor-pointer ${
          isSelected ? 'border-blue-500 shadow-lg' : 'border-gray-200 hover:border-gray-300'
        } ${currentLayout === 'list' ? 'flex' : ''}`}
        onClick={() => {
          setSelectedResult(result);
          onResultClick?.(result);
        }}
      >
        {/* 内容区域 */}
        <div className={`${currentLayout === 'list' ? 'flex-1' : ''}`}>
          {result.type === 'image' && result.url && (
            <div className="relative">
              <img
                src={result.url}
                alt={result.metadata?.filename || `Result ${index + 1}`}
                className={`w-full object-cover ${
                  currentLayout === 'list' ? 'h-24' : 'h-48'
                }`}
              />
              <div className="absolute top-2 left-2 bg-black bg-opacity-50 text-white px-2 py-1 rounded text-xs">
                {getTypeIcon(result.type)}
                <span className="ml-1">图片</span>
              </div>
            </div>
          )}

          {result.type === 'video' && result.url && (
            <div className="relative">
              <video
                src={result.url}
                className={`w-full object-cover ${
                  currentLayout === 'list' ? 'h-24' : 'h-48'
                }`}
                controls={currentLayout !== 'list'}
                poster={result.metadata?.filename}
              />
              <div className="absolute top-2 left-2 bg-black bg-opacity-50 text-white px-2 py-1 rounded text-xs">
                {getTypeIcon(result.type)}
                <span className="ml-1">视频</span>
              </div>
            </div>
          )}

          {result.type === 'audio' && result.url && (
            <div className="p-4 bg-gray-50 flex items-center justify-center h-32">
              <div className="text-center">
                <Music className="w-8 h-8 text-gray-400 mx-auto mb-2" />
                <audio src={result.url} controls className="w-full max-w-xs" />
              </div>
            </div>
          )}

          {result.type === 'text' && result.content && (
            <div className="p-4 bg-gray-50">
              <pre className="text-sm text-gray-700 whitespace-pre-wrap max-h-32 overflow-y-auto">
                {result.content}
              </pre>
            </div>
          )}

          {result.type === 'json' && result.content && (
            <div className="p-4 bg-gray-50">
              <pre className="text-xs text-gray-700 whitespace-pre-wrap max-h-32 overflow-y-auto font-mono">
                {JSON.stringify(JSON.parse(result.content), null, 2)}
              </pre>
            </div>
          )}

          {/* 元数据信息 */}
          <div className="p-3 border-t border-gray-100">
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-2">
                {getTypeIcon(result.type)}
                <span className="text-sm font-medium text-gray-900">
                  {result.metadata?.filename || `结果 ${index + 1}`}
                </span>
              </div>
              
              <div className="flex items-center space-x-2">
                {showFullscreen && (result.type === 'image' || result.type === 'video') && (
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      setSelectedResult(result);
                      setIsFullscreen(true);
                    }}
                    className="p-1 text-gray-400 hover:text-gray-600"
                    title="全屏查看"
                  >
                    <Maximize2 className="w-4 h-4" />
                  </button>
                )}
                
                {showDownload && result.url && (
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      downloadFile(result);
                    }}
                    className="p-1 text-gray-400 hover:text-blue-600"
                    title="下载"
                  >
                    <Download className="w-4 h-4" />
                  </button>
                )}
              </div>
            </div>

            {/* 详细信息 */}
            <div className="mt-2 text-xs text-gray-500 space-y-1">
              {result.metadata?.size && (
                <div>大小: {formatFileSize(result.metadata.size)}</div>
              )}
              {result.metadata?.duration && (
                <div>时长: {formatDuration(result.metadata.duration)}</div>
              )}
              {result.metadata?.dimensions && (
                <div>
                  尺寸: {result.metadata.dimensions.width} × {result.metadata.dimensions.height}
                </div>
              )}
              {result.metadata?.format && (
                <div>格式: {result.metadata.format.toUpperCase()}</div>
              )}
            </div>
          </div>
        </div>
      </div>
    );
  };

  if (results.length === 0) {
    return (
      <div className="text-center py-8 text-gray-500">
        <FileText className="w-12 h-12 mx-auto mb-4 text-gray-300" />
        <p>暂无执行结果</p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* 工具栏 */}
      <div className="flex items-center justify-between">
        <div className="text-sm text-gray-600">
          共 {results.length} 个结果
        </div>
        
        <div className="flex items-center space-x-2">
          <button
            onClick={() => setCurrentLayout('grid')}
            className={`p-2 rounded ${
              currentLayout === 'grid' 
                ? 'bg-blue-100 text-blue-600' 
                : 'text-gray-400 hover:text-gray-600'
            }`}
            title="网格布局"
          >
            <Grid className="w-4 h-4" />
          </button>
          
          <button
            onClick={() => setCurrentLayout('list')}
            className={`p-2 rounded ${
              currentLayout === 'list' 
                ? 'bg-blue-100 text-blue-600' 
                : 'text-gray-400 hover:text-gray-600'
            }`}
            title="列表布局"
          >
            <List className="w-4 h-4" />
          </button>
        </div>
      </div>

      {/* 结果列表 */}
      <div className={
        currentLayout === 'grid' 
          ? 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4'
          : 'space-y-4'
      }>
        {results.map((result, index) => renderResult(result, index))}
      </div>

      {/* 全屏模态框 */}
      {isFullscreen && selectedResult && (
        <div className="fixed inset-0 bg-black bg-opacity-90 z-50 flex items-center justify-center">
          <div className="relative max-w-full max-h-full">
            <button
              onClick={() => setIsFullscreen(false)}
              className="absolute top-4 right-4 text-white hover:text-gray-300 z-10"
            >
              <X className="w-6 h-6" />
            </button>
            
            {selectedResult.type === 'image' && selectedResult.url && (
              <img
                src={selectedResult.url}
                alt={selectedResult.metadata?.filename}
                className="max-w-full max-h-full object-contain"
              />
            )}
            
            {selectedResult.type === 'video' && selectedResult.url && (
              <video
                src={selectedResult.url}
                controls
                autoPlay
                className="max-w-full max-h-full"
              />
            )}
          </div>
        </div>
      )}
    </div>
  );
};
