import React, { useState } from 'react';
import {
  FileVideo,
  FileAudio,
  FileImage,
  Clock,
  ExternalLink,
  Play,
  Volume2,
  HardDrive
} from 'lucide-react';
import { GroundingSource } from '../types/ragGrounding';

/**
 * 聊天素材卡片属性接口
 */
interface ChatMaterialCardProps {
  /** 素材来源信息 */
  source: GroundingSource;
  /** 卡片大小 */
  size?: 'small' | 'medium' | 'large';
  /** 是否显示详细信息 */
  showDetails?: boolean;
  /** 自定义样式类名 */
  className?: string;
  /** 点击回调 */
  onClick?: (source: GroundingSource) => void;
}

/**
 * 格式化文件大小
 */
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(1)) + ' ' + sizes[i];
};

/**
 * 格式化时长
 */
const formatDuration = (seconds: number): string => {
  if (seconds < 60) {
    return `${Math.round(seconds)}s`;
  } else {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = Math.round(seconds % 60);
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
  }
};

/**
 * 获取文件类型图标
 */
const getFileTypeIcon = (type: string) => {
  switch (type.toLowerCase()) {
    case 'video':
      return <FileVideo className="w-4 h-4 text-blue-500" />;
    case 'audio':
      return <FileAudio className="w-4 h-4 text-green-500" />;
    case 'image':
      return <FileImage className="w-4 h-4 text-purple-500" />;
    default:
      return <FileImage className="w-4 h-4 text-gray-500" />;
  }
};

/**
 * 聊天素材卡片组件
 * 专为聊天界面优化的素材展示卡片
 */
export const ChatMaterialCard: React.FC<ChatMaterialCardProps> = ({
  source,
  size = 'medium',
  showDetails = true,
  className = '',
  onClick
}) => {
  const [imageError, setImageError] = useState(false);
  const [isHovered, setIsHovered] = useState(false);

  // 获取卡片尺寸样式
  const getSizeClasses = () => {
    switch (size) {
      case 'small':
        return 'w-32 h-24';
      case 'large':
        return 'w-64 h-48';
      default:
        return 'w-48 h-36';
    }
  };

  // 获取内容类型
  const contentType = source.content?.type || 'unknown';
  const isImage = contentType === 'image';
  const isVideo = contentType === 'video';
  const isAudio = contentType === 'audio';

  // 处理卡片点击
  const handleClick = () => {
    onClick?.(source);
  };

  return (
    <div
      className={`
        relative chat-material-card rounded-lg
        cursor-pointer overflow-hidden group
        ${getSizeClasses()}
        ${className}
      `}
      onClick={handleClick}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      {/* 缩略图/预览区域 */}
      <div className="relative w-full h-2/3 bg-gray-100 overflow-hidden">
        {isImage && source.content?.image_url && !imageError ? (
          <img
            src={source.content.image_url}
            alt={source.title || '素材图片'}
            className="w-full h-full object-cover"
            onError={() => setImageError(true)}
            loading="lazy"
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center bg-gradient-to-br from-gray-100 to-gray-200">
            {getFileTypeIcon(contentType)}
          </div>
        )}

        {/* 悬停播放按钮 */}
        {(isVideo || isAudio) && isHovered && (
          <div className="absolute inset-0 bg-black bg-opacity-30 flex items-center justify-center">
            <div className="bg-white bg-opacity-90 rounded-full p-2">
              {isVideo ? (
                <Play className="w-6 h-6 text-gray-700" />
              ) : (
                <Volume2 className="w-6 h-6 text-gray-700" />
              )}
            </div>
          </div>
        )}

        {/* 文件类型标识 */}
        <div className="absolute top-2 left-2">
          <div className="bg-black bg-opacity-60 rounded px-2 py-1 flex items-center space-x-1">
            {getFileTypeIcon(contentType)}
            <span className="text-white text-xs font-medium">
              {contentType.toUpperCase()}
            </span>
          </div>
        </div>

        {/* 时长标识 */}
        {(isVideo || isAudio) && source.content?.duration && (
          <div className="absolute bottom-2 right-2">
            <div className="bg-black bg-opacity-60 rounded px-2 py-1 flex items-center space-x-1">
              <Clock className="w-3 h-3 text-white" />
              <span className="text-white text-xs">
                {formatDuration(source.content.duration)}
              </span>
            </div>
          </div>
        )}
      </div>

      {/* 信息区域 */}
      <div className="p-3 h-1/3 flex flex-col justify-between">
        <div className="flex-1">
          <h4 className="text-sm font-medium text-gray-900 truncate">
            {source.title || '未知素材'}
          </h4>
          
          {showDetails && source.content?.description && (
            <p className="text-xs text-gray-600 mt-1 line-clamp-2">
              {source.content.description}
            </p>
          )}
        </div>

        {/* 底部信息 */}
        {showDetails && (
          <div className="flex items-center justify-between mt-2 text-xs text-gray-500">
            <div className="flex items-center space-x-2">
              {source.content?.file_size && (
                <div className="flex items-center space-x-1">
                  <HardDrive className="w-3 h-3" />
                  <span>{formatFileSize(source.content.file_size)}</span>
                </div>
              )}
            </div>
            
            {source.uri && (
              <div className="flex items-center space-x-1">
                <ExternalLink className="w-3 h-3" />
                <span className="truncate max-w-16">
                  {source.uri.split('/').pop()}
                </span>
              </div>
            )}
          </div>
        )}
      </div>

      {/* 悬停效果 */}
      {isHovered && (
        <div className="absolute inset-0 bg-blue-500 bg-opacity-5 pointer-events-none" />
      )}
    </div>
  );
};

export default ChatMaterialCard;
