import React from 'react';
import {
  EyeIcon,
  PencilIcon,
  TrashIcon,
  PlayIcon,
  MusicalNoteIcon,
  DocumentTextIcon,
  PhotoIcon,
  VideoCameraIcon
} from '@heroicons/react/24/outline';
import { 
  MaterialAsset, 
  MATERIAL_CATEGORY_CONFIG 
} from '../../types/videoGeneration';

interface MaterialAssetCardProps {
  asset: MaterialAsset;
  viewMode?: 'grid' | 'list';
  isSelected?: boolean;
  onSelect?: (asset: MaterialAsset) => void;
  onPreview?: (asset: MaterialAsset) => void;
  onEdit?: (asset: MaterialAsset) => void;
  onDelete?: (asset: MaterialAsset) => void;
  showActions?: boolean;
}

/**
 * 素材卡片组件
 * 遵循 UI/UX 设计标准，支持网格和列表两种视图模式
 */
export const MaterialAssetCard: React.FC<MaterialAssetCardProps> = ({
  asset,
  viewMode = 'grid',
  isSelected = false,
  onSelect,
  onPreview,
  onEdit,
  onDelete,
  showActions = true
}) => {
  const categoryConfig = MATERIAL_CATEGORY_CONFIG[asset.category];

  // 获取文件类型图标
  const getTypeIcon = () => {
    switch (asset.type) {
      case 'image':
        return <PhotoIcon className="h-5 w-5" />;
      case 'video':
        return <VideoCameraIcon className="h-5 w-5" />;
      case 'audio':
        return <MusicalNoteIcon className="h-5 w-5" />;
      case 'text':
        return <DocumentTextIcon className="h-5 w-5" />;
      default:
        return <DocumentTextIcon className="h-5 w-5" />;
    }
  };

  // 格式化文件大小
  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 = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  // 网格视图
  if (viewMode === 'grid') {
    return (
      <div
        className={`group relative dynamic-card hover-lift cursor-pointer overflow-hidden ${
          isSelected ? 'ring-2 ring-primary-500 border-primary-300 shadow-medium' : ''
        }`}
        onClick={() => onSelect?.(asset)}
      >
        {/* 缩略图区域 */}
        <div className="aspect-video thumbnail-container relative overflow-hidden">
          {asset.thumbnail_path ? (
            <img
              src={asset.thumbnail_path}
              alt={asset.name}
              className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
            />
          ) : (
            <div className="w-full h-full flex-center">
              <div className={`icon-container w-12 h-12 ${categoryConfig.bgColor.replace('bg-', '')}`}>
                <span className="text-2xl">{categoryConfig.icon}</span>
              </div>
            </div>
          )}

          {/* 类型标识 */}
          <div className="absolute top-2 left-2">
            <div className={`badge ${categoryConfig.bgColor} ${categoryConfig.color} backdrop-blur-sm shadow-subtle`}>
              {getTypeIcon()}
              <span className="ml-1">{categoryConfig.label}</span>
            </div>
          </div>

          {/* 播放按钮（视频/音频） */}
          {(asset.type === 'video' || asset.type === 'audio') && (
            <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200">
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  onPreview?.(asset);
                }}
                className="p-3 bg-black/50 text-white rounded-full hover:bg-black/70 transition-colors duration-200"
              >
                <PlayIcon className="h-6 w-6" />
              </button>
            </div>
          )}

          {/* 操作按钮 */}
          {showActions && (
            <div className="absolute top-2 right-2 visible-on-hover">
              <div className="flex items-center gap-1">
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    onPreview?.(asset);
                  }}
                  className="touch-target p-1.5 glass-effect text-gray-700 rounded-md hover:bg-white/90 transition-all duration-200 shadow-subtle hover:shadow-medium"
                  title="预览"
                >
                  <EyeIcon className="h-4 w-4" />
                </button>
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    onEdit?.(asset);
                  }}
                  className="touch-target p-1.5 glass-effect text-gray-700 rounded-md hover:bg-white/90 transition-all duration-200 shadow-subtle hover:shadow-medium"
                  title="编辑"
                >
                  <PencilIcon className="h-4 w-4" />
                </button>
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    onDelete?.(asset);
                  }}
                  className="touch-target p-1.5 glass-effect text-red-600 rounded-md hover:bg-red-50 transition-all duration-200 shadow-subtle hover:shadow-medium"
                  title="删除"
                >
                  <TrashIcon className="h-4 w-4" />
                </button>
              </div>
            </div>
          )}
        </div>

        {/* 内容区域 */}
        <div className="p-4">
          <h3 className="text-heading-6 text-high-emphasis text-ellipsis mb-1">
            {asset.name}
          </h3>

          {asset.description && (
            <p className="text-body-small text-medium-emphasis line-clamp-2 mb-2">
              {asset.description}
            </p>
          )}

          {/* 元数据 */}
          <div className="flex items-center justify-between text-caption text-low-emphasis">
            <div className="flex items-center gap-2">
              {asset.metadata?.duration && (
                <span className="badge-secondary">{formatDuration(asset.metadata.duration)}</span>
              )}
              {asset.metadata?.size && (
                <span className="badge-secondary">{formatFileSize(asset.metadata.size)}</span>
              )}
              {asset.metadata?.width && asset.metadata?.height && (
                <span className="badge-secondary">{asset.metadata.width}×{asset.metadata.height}</span>
              )}
            </div>
          </div>

          {/* 标签 */}
          {asset.tags.length > 0 && (
            <div className="flex flex-wrap gap-1 mt-2">
              {asset.tags.slice(0, 3).map((tag, index) => (
                <span
                  key={index}
                  className="badge badge-secondary"
                >
                  {tag}
                </span>
              ))}
              {asset.tags.length > 3 && (
                <span className="badge badge-secondary">
                  +{asset.tags.length - 3}
                </span>
              )}
            </div>
          )}
        </div>
      </div>
    );
  }

  // 列表视图
  return (
    <div
      className={`group bg-white rounded-lg shadow-sm border border-gray-200 hover:shadow-md transition-all duration-200 overflow-hidden cursor-pointer ${
        isSelected ? 'ring-2 ring-primary-500 border-primary-300' : ''
      }`}
      onClick={() => onSelect?.(asset)}
    >
      <div className="flex items-center p-4">
        {/* 缩略图 */}
        <div className="flex-shrink-0 w-16 h-16 bg-gradient-to-br from-gray-100 to-gray-200 rounded-lg overflow-hidden">
          {asset.thumbnail_path ? (
            <img
              src={asset.thumbnail_path}
              alt={asset.name}
              className="w-full h-full object-cover"
            />
          ) : (
            <div className="w-full h-full flex items-center justify-center">
              <span className="text-lg">{categoryConfig.icon}</span>
            </div>
          )}
        </div>

        {/* 内容 */}
        <div className="flex-1 ml-4 min-w-0">
          <div className="flex items-center gap-2 mb-1">
            <h3 className="font-medium text-gray-900 truncate">
              {asset.name}
            </h3>
            <div className={`flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium ${categoryConfig.bgColor} ${categoryConfig.color}`}>
              {getTypeIcon()}
              <span>{categoryConfig.label}</span>
            </div>
          </div>
          
          {asset.description && (
            <p className="text-sm text-gray-600 truncate mb-2">
              {asset.description}
            </p>
          )}

          <div className="flex items-center gap-4 text-xs text-gray-500">
            {asset.metadata?.duration && (
              <span>{formatDuration(asset.metadata.duration)}</span>
            )}
            {asset.metadata?.size && (
              <span>{formatFileSize(asset.metadata.size)}</span>
            )}
            {asset.metadata?.width && asset.metadata?.height && (
              <span>{asset.metadata.width}×{asset.metadata.height}</span>
            )}
          </div>
        </div>

        {/* 标签 */}
        <div className="flex-shrink-0 ml-4">
          <div className="flex flex-wrap gap-1 justify-end">
            {asset.tags.slice(0, 2).map((tag, index) => (
              <span
                key={index}
                className="px-2 py-1 bg-gray-100 text-gray-600 text-xs rounded-md"
              >
                {tag}
              </span>
            ))}
          </div>
        </div>

        {/* 操作按钮 */}
        {showActions && (
          <div className="flex-shrink-0 ml-4 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
            <div className="flex items-center gap-1">
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  onPreview?.(asset);
                }}
                className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-md transition-colors duration-200"
                title="预览"
              >
                <EyeIcon className="h-4 w-4" />
              </button>
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  onEdit?.(asset);
                }}
                className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-md transition-colors duration-200"
                title="编辑"
              >
                <PencilIcon className="h-4 w-4" />
              </button>
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  onDelete?.(asset);
                }}
                className="p-2 text-red-500 hover:text-red-700 hover:bg-red-50 rounded-md transition-colors duration-200"
                title="删除"
              >
                <TrashIcon className="h-4 w-4" />
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};
