import React, { useState, useCallback } from 'react';
import {
  Star,
  Tag,
  Palette,
  ExternalLink,
  Eye,
  ChevronRight,
  Package,
  Sparkles,
} from 'lucide-react';
import { MaterialCardProps } from '../../types/outfitRecommendation';
import MaterialSearchService from '../../services/materialSearchService';

/**
 * 素材卡片组件
 * 遵循设计系统规范，提供统一的素材展示界面
 */
const MaterialCard: React.FC<MaterialCardProps> = ({
  material,
  onSelect,
  showScore = true,
  compact = false,
  className = '',
}) => {
  const [imageLoaded, setImageLoaded] = useState(false);
  const [imageError, setImageError] = useState(false);
  const [isHovered, setIsHovered] = useState(false);

  // 处理卡片点击
  const handleCardClick = useCallback((e: React.MouseEvent) => {
    // 如果点击的是按钮或其子元素，不触发卡片选择
    const target = e.target as HTMLElement;
    if (target.closest('button')) {
      return;
    }

    if (onSelect) {
      onSelect(material);
    }
  }, [material, onSelect]);

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

  // 处理图片错误
  const handleImageError = useCallback(() => {
    setImageError(true);
    setImageLoaded(true);
  }, []);

  // 处理外部链接点击
  const handleExternalLink = useCallback((e: React.MouseEvent) => {
    e.stopPropagation();
    if (material.image_url) {
      window.open(material.image_url, '_blank');
    }
  }, [material.image_url]);

  // 获取主要产品信息
  const primaryProduct = material.products[0];
  const hasMultipleProducts = material.products.length > 1;

  // 列表视图的特殊布局
  if (compact) {
    return (
      <div
        className={`
          card card-interactive group cursor-pointer animate-fade-in-up
          relative overflow-hidden bg-gradient-to-br from-white to-gray-50/50
          hover:from-white hover:to-primary-50/30 transition-all duration-300
          hover:shadow-md hover:shadow-primary-500/10
          border border-gray-200 hover:border-primary-300
          p-4 flex items-center gap-4
          ${className}
        `}
        onClick={handleCardClick}
        onMouseEnter={() => setIsHovered(true)}
        onMouseLeave={() => setIsHovered(false)}
      >
        {/* 装饰性背景 */}
        <div className="absolute top-0 right-0 w-16 h-16 bg-gradient-to-br from-primary-100 to-primary-200 rounded-full -translate-y-8 translate-x-8 opacity-40 group-hover:opacity-60 transition-all duration-500"></div>

        {/* 左侧图片 */}
        <div className="relative flex-shrink-0">
          <div className="w-20 h-20 rounded-lg overflow-hidden bg-gray-100">
            {!imageError ? (
              <img
                src={material.image_url}
                alt={material.style_description}
                className={`w-full h-full object-cover transition-all duration-300 group-hover:scale-105 ${
                  imageLoaded ? 'opacity-100' : 'opacity-0'
                }`}
                onLoad={handleImageLoad}
                onError={handleImageError}
              />
            ) : (
              <div className="w-full h-full flex items-center justify-center bg-gray-100">
                <Package className="w-6 h-6 text-gray-400" />
              </div>
            )}

            {/* 加载状态 */}
            {!imageLoaded && !imageError && (
              <div className="absolute inset-0 flex items-center justify-center bg-gray-100">
                <div className="w-4 h-4 border-2 border-primary-500 border-t-transparent rounded-full animate-spin"></div>
              </div>
            )}
          </div>

          {/* 评分标识 */}
          {showScore && (
            <div className="absolute -top-2 -right-2 flex items-center gap-1 px-2 py-1 bg-yellow-100 text-yellow-700 rounded-full text-xs font-medium">
              <Star className="w-3 h-3 fill-current" />
              {MaterialSearchService.formatRelevanceScore(material.relevance_score)}
            </div>
          )}
        </div>

        {/* 中间内容 */}
        <div className="flex-1 min-w-0 space-y-2">
          {/* 标题和描述 */}
          <div>
            <h3 className="text-sm font-semibold text-high-emphasis line-clamp-1 group-hover:text-primary-600 transition-colors duration-200">
              {material.style_description || '时尚素材'}
            </h3>
            {primaryProduct && (
              <p className="text-xs text-gray-600 line-clamp-1 mt-1">
                {primaryProduct.description}
              </p>
            )}
          </div>

          {/* 标签行 */}
          <div className="flex items-center gap-2 flex-wrap">
            {/* 类别标签 */}
            {primaryProduct && (
              <div className="flex items-center gap-1">
                <Tag className="w-3 h-3 text-gray-500" />
                <span className="text-xs font-medium text-gray-700">{primaryProduct.category}</span>
                {hasMultipleProducts && (
                  <span className="text-xs text-gray-500">+{material.products.length - 1}</span>
                )}
              </div>
            )}

            {/* 环境标签 */}
            {material.environment_tags.slice(0, 2).map((tag, index) => (
              <div
                key={index}
                className="px-2 py-0.5 bg-blue-100 text-blue-700 rounded text-xs"
              >
                {tag}
              </div>
            ))}
            {material.environment_tags.length > 2 && (
              <div className="px-2 py-0.5 bg-gray-100 text-gray-500 rounded text-xs">
                +{material.environment_tags.length - 2}
              </div>
            )}
          </div>

          {/* 设计风格 */}
          {primaryProduct && primaryProduct.design_styles.length > 0 && (
            <div className="flex flex-wrap gap-1">
              {primaryProduct.design_styles.slice(0, 3).map((style, index) => (
                <div
                  key={index}
                  className="px-2 py-0.5 bg-gray-100 text-gray-600 rounded text-xs"
                >
                  {style}
                </div>
              ))}
              {primaryProduct.design_styles.length > 3 && (
                <div className="px-2 py-0.5 bg-gray-100 text-gray-500 rounded text-xs">
                  +{primaryProduct.design_styles.length - 3}
                </div>
              )}
            </div>
          )}
        </div>

        {/* 右侧操作区域 */}
        <div className="flex-shrink-0 flex flex-col items-end gap-2">
          {/* 颜色信息 */}
          {primaryProduct && (
            <div className="flex items-center gap-2">
              <Palette className="w-3 h-3 text-gray-500" />
              <div
                className="w-4 h-4 rounded-full border border-gray-300 shadow-sm"
                style={{
                  backgroundColor: `hsl(${primaryProduct.color_pattern.hue * 360}, ${primaryProduct.color_pattern.saturation * 100}%, ${primaryProduct.color_pattern.value * 100}%)`
                }}
                title="主要颜色"
              />
            </div>
          )}

          {/* 操作按钮 */}
          <button
            onClick={(e) => {
              e.stopPropagation();
              if (onSelect) onSelect(material);
            }}
            className="flex items-center gap-1 px-3 py-1 text-primary-600 hover:text-primary-700 hover:bg-primary-50 rounded transition-colors duration-200 text-xs font-medium"
          >
            <Eye className="w-3 h-3" />
            查看
            <ChevronRight className="w-3 h-3" />
          </button>

          {/* 时间信息 */}
          <div className="text-xs text-gray-500">
            {new Date(material.created_at).toLocaleDateString()}
          </div>
        </div>

        {/* AI推荐标识 */}
        <div className="absolute bottom-2 left-4 flex items-center gap-1 px-2 py-1 bg-gradient-to-r from-purple-100 to-pink-100 text-purple-700 rounded-full text-xs font-medium opacity-0 group-hover:opacity-100 transition-opacity duration-300">
          <Sparkles className="w-3 h-3" />
          AI推荐
        </div>
      </div>
    );
  }

  // 网格视图的原有布局
  return (
    <div
      className={`
        card card-interactive group cursor-pointer animate-fade-in-up
        relative overflow-hidden bg-gradient-to-br from-white to-gray-50/50
        hover:from-white hover:to-primary-50/30 transition-all duration-500
        hover:shadow-lg hover:shadow-primary-500/10 hover:-translate-y-1
        border border-gray-200 hover:border-primary-300
        transform-gpu will-change-transform
        p-5
        ${className}
      `}
      onClick={handleCardClick}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      {/* 装饰性背景 */}
      <div className="absolute top-0 right-0 w-20 h-20 bg-gradient-to-br from-primary-100 to-primary-200 rounded-full -translate-y-10 translate-x-10 opacity-40 group-hover:opacity-60 transition-all duration-500 group-hover:scale-110"></div>

      {/* 顶部标识 */}
      <div className="absolute top-3 right-3 flex items-center gap-2">
        {showScore && (
          <div className="flex items-center gap-1 px-2 py-1 bg-yellow-100 text-yellow-700 rounded-full text-xs font-medium">
            <Star className="w-3 h-3 fill-current" />
            {MaterialSearchService.formatRelevanceScore(material.relevance_score)}
          </div>
        )}
      </div>

      <div className="relative">
        {/* 素材图片 */}
        <div className="relative mb-4">
          <div className={`aspect-square rounded-lg overflow-hidden bg-gray-100 ${compact ? 'h-32' : 'h-48'}`}>
            {!imageError ? (
              <img
                src={material.image_url}
                alt={material.style_description}
                className={`w-full h-full object-cover transition-all duration-500 group-hover:scale-105 ${
                  imageLoaded ? 'opacity-100' : 'opacity-0'
                }`}
                onLoad={handleImageLoad}
                onError={handleImageError}
              />
            ) : (
              <div className="w-full h-full flex items-center justify-center bg-gray-100">
                <Package className="w-8 h-8 text-gray-400" />
              </div>
            )}
            
            {/* 加载状态 */}
            {!imageLoaded && !imageError && (
              <div className="absolute inset-0 flex items-center justify-center bg-gray-100">
                <div className="w-6 h-6 border-2 border-primary-500 border-t-transparent rounded-full animate-spin"></div>
              </div>
            )}

            {/* 悬停遮罩 */}
            {isHovered && (
              <div className="absolute inset-0 bg-black/20 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-300">
                <button
                  onClick={handleExternalLink}
                  className="flex items-center gap-2 px-3 py-2 bg-white/90 text-gray-800 rounded-lg hover:bg-white transition-colors duration-200"
                >
                  <ExternalLink className="w-4 h-4" />
                  <span className="text-sm font-medium">查看原图</span>
                </button>
              </div>
            )}
          </div>
        </div>

        {/* 素材信息 */}
        <div className="space-y-3">
          {/* 风格描述 */}
          <div>
            <h3 className="text-sm font-semibold text-high-emphasis line-clamp-2 group-hover:text-primary-600 transition-colors duration-200">
              {material.style_description || '时尚素材'}
            </h3>
          </div>

          {/* 环境标签 */}
          {material.environment_tags.length > 0 && (
            <div className="flex flex-wrap gap-1">
              {material.environment_tags.slice(0, 2).map((tag, index) => (
                <div
                  key={index}
                  className="px-2 py-1 bg-blue-100 text-blue-700 rounded-full text-xs font-medium"
                >
                  {tag}
                </div>
              ))}
              {material.environment_tags.length > 2 && (
                <div className="px-2 py-1 bg-gray-100 text-gray-500 rounded-full text-xs">
                  +{material.environment_tags.length - 2}
                </div>
              )}
            </div>
          )}

          {/* 产品信息 */}
          {primaryProduct && (
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <Tag className="w-3 h-3 text-gray-500" />
                <span className="text-xs font-medium text-gray-700">{primaryProduct.category}</span>
                {hasMultipleProducts && (
                  <span className="text-xs text-gray-500">+{material.products.length - 1}</span>
                )}
              </div>
              
              <p className="text-xs text-gray-600 line-clamp-2">
                {primaryProduct.description}
              </p>

              {/* 设计风格 */}
              {primaryProduct.design_styles.length > 0 && (
                <div className="flex flex-wrap gap-1">
                  {primaryProduct.design_styles.slice(0, 2).map((style, index) => (
                    <div
                      key={index}
                      className="px-2 py-0.5 bg-gray-100 text-gray-600 rounded text-xs"
                    >
                      {style}
                    </div>
                  ))}
                  {primaryProduct.design_styles.length > 2 && (
                    <div className="px-2 py-0.5 bg-gray-100 text-gray-500 rounded text-xs">
                      +{primaryProduct.design_styles.length - 2}
                    </div>
                  )}
                </div>
              )}
            </div>
          )}

          {/* 颜色信息 */}
          {primaryProduct && (
            <div className="flex items-center gap-2">
              <Palette className="w-3 h-3 text-gray-500" />
              <div
                className="w-4 h-4 rounded-full border border-gray-300 shadow-sm"
                style={{
                  backgroundColor: `hsl(${primaryProduct.color_pattern.hue * 360}, ${primaryProduct.color_pattern.saturation * 100}%, ${primaryProduct.color_pattern.value * 100}%)`
                }}
                title="主要颜色"
              />
              <span className="text-xs text-gray-600">主色调</span>
            </div>
          )}
        </div>

        {/* 底部操作区域 */}
        <div className="flex items-center justify-between pt-3 mt-3 border-t border-gray-100">
          <div className="text-xs text-gray-500">
            {new Date(material.created_at).toLocaleDateString()}
          </div>
          
          <button
            onClick={(e) => {
              e.stopPropagation();
              if (onSelect) onSelect(material);
            }}
            className="flex items-center gap-1 px-2 py-1 text-primary-600 hover:text-primary-700 hover:bg-primary-50 rounded transition-colors duration-200 text-xs font-medium"
          >
            <Eye className="w-3 h-3" />
            查看详情
            <ChevronRight className="w-3 h-3" />
          </button>
        </div>
      </div>

      {/* AI推荐标识 */}
      <div className="absolute bottom-3 left-3 flex items-center gap-1 px-2 py-1 bg-gradient-to-r from-purple-100 to-pink-100 text-purple-700 rounded-full text-xs font-medium opacity-0 group-hover:opacity-100 transition-opacity duration-300">
        <Sparkles className="w-3 h-3" />
        AI推荐
      </div>
    </div>
  );
};

export default MaterialCard;
