import React, { useState, useCallback } from 'react';
import {
  Download,
  ExternalLink,
  X,
  Calendar,
  MapPin,
  User,
  Shirt,
  AlertCircle
} from 'lucide-react';
import { GroundingSource } from '../types/ragGrounding';

/**
 * 图片卡片属性接口
 */
interface ImageCardProps {
  /** Grounding 来源数据 */
  source: GroundingSource;
  /** 是否显示详细信息 */
  showDetails?: boolean;
  /** 卡片位置样式 */
  position?: {
    top?: number;
    left?: number;
    right?: number;
    bottom?: number;
  };
  /** 关闭回调 */
  onClose?: () => void;
  /** 下载回调 */
  onDownload?: (source: GroundingSource) => void;
  /** 查看大图回调 */
  onViewLarge?: (source: GroundingSource) => void;
  /** 自定义样式类名 */
  className?: string;
  /** 已选中的标签列表 */
  selectedTags?: string[];
  /** 标签点击回调 */
  onTagClick?: (tag: string) => void;
}

/**
 * 图片卡片组件
 * 遵循 ag-ui 设计标准，支持图片展示、信息显示和下载功能
 */
export const ImageCard: React.FC<ImageCardProps> = ({
  source,
  showDetails = true,
  position,
  onClose,
  onDownload,
  className = '',
  selectedTags = [],
  onTagClick
}) => {
  const [imageLoaded, setImageLoaded] = useState(false);
  const [imageError, setImageError] = useState(false);
  const [isDownloading, setIsDownloading] = useState(false);
  const [expandedEnvironmentTags, setExpandedEnvironmentTags] = useState(false);
  const [expandedCategories, setExpandedCategories] = useState(false);

  // 解析图片内容
  const imageData = source.content?.text || source.content;
  const imageUri = source.uri;
  const title = source.title || '时尚图片';

  // 提取图片信息
  const description = imageData?.description || '';
  const models = imageData?.models || [];
  const environmentTags = imageData?.environment_tags || [];
  const categories = imageData?.categories || [];
  const releaseDate = imageData?.releaseDate;

  // 处理图片加载
  const handleImageLoad = useCallback(() => {
    setImageLoaded(true);
    setImageError(false);
  }, []);

  const handleImageError = useCallback(() => {
    setImageError(true);
    setImageLoaded(false);
  }, []);

  // 处理下载
  const handleDownload = useCallback(async () => {
    if (!onDownload || isDownloading) return;
    
    setIsDownloading(true);
    try {
      await onDownload(source);
    } catch (error) {
      console.error('下载失败:', error);
    } finally {
      setIsDownloading(false);
    }
  }, [onDownload, source, isDownloading]);

  // 构建位置样式
  const positionStyle = position ? {
    position: 'absolute' as const,
    top: position.top,
    left: position.left,
    right: position.right,
    bottom: position.bottom,
    zIndex: 1000
  } : {};

  return (
    <div
      className={`bg-white rounded-xl shadow-lg border border-gray-200 overflow-hidden max-w-sm group ${className}`}
      style={positionStyle}
    >
      {/* 图片展示区域 */}
      <div className="relative bg-gray-50">
        {imageUri && !imageError ? (
          <div className="relative">
            <img
              src={imageUri}
              alt={description || title}
              className={`w-full max-h-64 object-contain transition-all duration-300 ${
                imageLoaded ? 'opacity-100' : 'opacity-0'
              } group-hover:scale-105`}
              onLoad={handleImageLoad}
              onError={handleImageError}
            />

            {/* 悬浮按钮组 */}
            <div className="absolute top-2 right-2 flex items-center space-x-1 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
              {onDownload && (
                <button
                  onClick={handleDownload}
                  disabled={isDownloading}
                  className="p-2 bg-black/50 hover:bg-black/70 text-white rounded-full backdrop-blur-sm transition-all duration-200 hover:scale-110 disabled:opacity-50 disabled:cursor-not-allowed"
                  title="下载到本地"
                >
                  <Download className={`w-4 h-4 ${isDownloading ? 'animate-pulse' : ''}`} />
                </button>
              )}
              {imageUri && (
                <a
                  href={imageUri}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="p-2 bg-black/50 hover:bg-black/70 text-white rounded-full backdrop-blur-sm transition-all duration-200 hover:scale-110"
                  title="在新窗口打开"
                >
                  <ExternalLink className="w-4 h-4" />
                </a>
              )}
              {onClose && (
                <button
                  onClick={onClose}
                  className="p-2 bg-black/50 hover:bg-black/70 text-white rounded-full backdrop-blur-sm transition-all duration-200 hover:scale-110"
                  title="关闭"
                >
                  <X className="w-4 h-4" />
                </button>
              )}
            </div>

            {/* 加载指示器 */}
            {!imageLoaded && (
              <div className="absolute inset-0 flex items-center justify-center bg-gray-100">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-pink-500"></div>
              </div>
            )}
          </div>
        ) : (
          <div className="min-h-32 max-h-64 flex items-center justify-center text-gray-400 bg-gray-100">
            <div className="text-center">
              <AlertCircle className="w-8 h-8 mx-auto mb-2" />
              <p className="text-sm">图片无法加载</p>
            </div>
          </div>
        )}
      </div>

      {/* 详细信息区域 */}
      {showDetails && (
        <div className="p-4 space-y-3">
          {/* 描述 */}
          {description && (
            <p className="text-sm text-gray-700 line-clamp-2 leading-relaxed">{description}</p>
          )}

          {/* 标签和信息 */}
          <div className="space-y-2">
            {/* 环境标签 */}
            {environmentTags.length > 0 && (
              <div className="flex items-start space-x-2">
                <MapPin className="w-3 h-3 text-gray-400 mt-0.5 flex-shrink-0" />
                <div className="flex flex-wrap gap-1 min-w-0">
                  {(expandedEnvironmentTags ? environmentTags : environmentTags.slice(0, 2)).map((tag: string, index: number) => {
                    const isSelected = selectedTags.includes(tag);
                    return (
                      <button
                        key={index}
                        onClick={() => onTagClick?.(tag)}
                        className={`px-2 py-1 text-xs rounded-md font-medium transition-all duration-200 cursor-pointer ${
                          isSelected
                            ? 'bg-pink-500 text-white shadow-md transform scale-105'
                            : 'bg-blue-50 text-blue-700 hover:bg-pink-100 hover:text-pink-700'
                        }`}
                      >
                        {tag}
                      </button>
                    );
                  })}
                  {environmentTags.length > 2 && (
                    <button
                      onClick={() => setExpandedEnvironmentTags(!expandedEnvironmentTags)}
                      className="text-xs text-gray-500 hover:text-gray-700 py-1 cursor-pointer transition-colors"
                    >
                      {expandedEnvironmentTags ? '收起' : `+${environmentTags.length - 2}`}
                    </button>
                  )}
                </div>
              </div>
            )}

            {/* 服装类别 */}
            {categories.length > 0 && (
              <div className="flex items-start space-x-2">
                <Shirt className="w-3 h-3 text-gray-400 mt-0.5 flex-shrink-0" />
                <div className="flex flex-wrap gap-1 min-w-0">
                  {(expandedCategories ? categories : categories.slice(0, 2)).map((category: string, index: number) => {
                    const isSelected = selectedTags.includes(category);
                    return (
                      <button
                        key={index}
                        onClick={() => onTagClick?.(category)}
                        className={`px-2 py-1 text-xs rounded-md font-medium transition-all duration-200 cursor-pointer ${
                          isSelected
                            ? 'bg-pink-500 text-white shadow-md transform scale-105'
                            : 'bg-pink-50 text-pink-700 hover:bg-pink-100 hover:text-pink-800'
                        }`}
                      >
                        {category}
                      </button>
                    );
                  })}
                  {categories.length > 2 && (
                    <button
                      onClick={() => setExpandedCategories(!expandedCategories)}
                      className="text-xs text-gray-500 hover:text-gray-700 py-1 cursor-pointer transition-colors"
                    >
                      {expandedCategories ? '收起' : `+${categories.length - 2}`}
                    </button>
                  )}
                </div>
              </div>
            )}

            {/* 底部信息行 */}
            <div className="flex items-center justify-between pt-1 border-t border-gray-100">
              {/* 模特信息 */}
              {models.length > 0 && (
                <div className="flex items-center space-x-1">
                  <User className="w-3 h-3 text-gray-400" />
                  <span className="text-xs text-gray-600 font-medium">
                    {models.length} 位模特
                  </span>
                </div>
              )}

              {/* 发布时间 */}
              {releaseDate && (
                <div className="flex items-center space-x-1">
                  <Calendar className="w-3 h-3 text-gray-400" />
                  <span className="text-xs text-gray-500">
                    {new Date(releaseDate).toLocaleDateString('zh-CN')}
                  </span>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ImageCard;
