import React, { useState, useCallback } from 'react';
import { OutfitCardProps } from '../../types/outfitSearch';
import { ColorUtils } from '../../utils/colorUtils';
import OutfitSearchService from '../../services/outfitSearchService';

/**
 * 服装搭配卡片组件
 * 遵循 Tauri 开发规范的组件设计原则
 */
export const OutfitCard: React.FC<OutfitCardProps> = ({
  result,
  onSelect,
  showScore = false,
}) => {
  const [imageLoaded, setImageLoaded] = useState(false);
  const [imageError, setImageError] = useState(false);

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

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

  // 处理卡片点击
  const handleCardClick = useCallback(() => {
    if (onSelect) {
      onSelect(result);
    }
  }, [result, onSelect]);

  // 获取主要产品类别
  const getMainCategories = useCallback(() => {
    const categories = result.products.map(p => p.category);
    const uniqueCategories = Array.from(new Set(categories));
    return uniqueCategories.slice(0, 3); // 最多显示3个类别
  }, [result.products]);

  // 获取主要颜色
  const getMainColors = useCallback(() => {
    const colors = result.products.map(p => p.color_pattern);
    return colors.slice(0, 4); // 最多显示4个颜色
  }, [result.products]);

  // 获取设计风格
  const getDesignStyles = useCallback(() => {
    const styles = result.products.flatMap(p => p.design_styles);
    const uniqueStyles = Array.from(new Set(styles));
    return uniqueStyles.slice(0, 3); // 最多显示3个风格
  }, [result.products]);

  const mainCategories = getMainCategories();
  const mainColors = getMainColors();
  const designStyles = getDesignStyles();

  return (
    <div 
      className={`outfit-card ${onSelect ? 'clickable' : ''}`}
      onClick={handleCardClick}
    >
      {/* 图片区域 */}
      <div className="card-image-container">
        {!imageLoaded && !imageError && (
          <div className="image-placeholder">
            <div className="loading-spinner" />
          </div>
        )}
        
        {imageError && (
          <div className="image-placeholder error">
            <svg className="error-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
              <circle cx="8.5" cy="8.5" r="1.5" />
              <polyline points="21,15 16,10 5,21" />
            </svg>
            <span>图片加载失败</span>
          </div>
        )}
        
        <img
          src={result.image_url}
          alt={result.style_description}
          className={`card-image ${imageLoaded ? 'loaded' : ''}`}
          onLoad={handleImageLoad}
          onError={handleImageError}
          style={{ display: imageError ? 'none' : 'block' }}
        />

        {/* 相关性评分 */}
        {showScore && (
          <div className="score-badge">
            {OutfitSearchService.formatRelevanceScore(result.relevance_score)}
          </div>
        )}
      </div>

      {/* 内容区域 */}
      <div className="card-content">
        {/* 风格描述 */}
        <h3 className="style-description">
          {result.style_description || '时尚搭配'}
        </h3>

        {/* 类别标签 */}
        {mainCategories.length > 0 && (
          <div className="categories">
            {mainCategories.map((category, index) => (
              <span key={index} className="category-tag">
                {category}
              </span>
            ))}
          </div>
        )}

        {/* 颜色调色板 */}
        {mainColors.length > 0 && (
          <div className="color-palette">
            <span className="palette-label">主要颜色</span>
            <div className="color-swatches">
              {mainColors.map((color, index) => (
                <div
                  key={index}
                  className="color-swatch"
                  style={{ backgroundColor: ColorUtils.hsvToHex(color) }}
                  title={`颜色 ${index + 1}: ${ColorUtils.hsvToHex(color)}`}
                />
              ))}
            </div>
          </div>
        )}

        {/* 设计风格 */}
        {designStyles.length > 0 && (
          <div className="design-styles">
            {designStyles.map((style, index) => (
              <span key={index} className="style-tag">
                {style}
              </span>
            ))}
          </div>
        )}

        {/* 环境标签 */}
        {result.environment_tags.length > 0 && (
          <div className="environment-tags">
            <span className="env-label">环境</span>
            <div className="env-tags">
              {result.environment_tags.slice(0, 2).map((tag, index) => (
                <span key={index} className="env-tag">
                  {tag}
                </span>
              ))}
              {result.environment_tags.length > 2 && (
                <span className="env-tag more">
                  +{result.environment_tags.length - 2}
                </span>
              )}
            </div>
          </div>
        )}
      </div>

      <style>{`
        .outfit-card {
          background: white;
          border-radius: 12px;
          overflow: hidden;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          border: 1px solid #e5e7eb;
          transition: all 0.2s;
        }

        .outfit-card.clickable {
          cursor: pointer;
        }

        .outfit-card.clickable:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
        }

        .card-image-container {
          position: relative;
          width: 100%;
          height: 200px;
          background: #f9fafb;
          overflow: hidden;
        }

        .image-placeholder {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          color: #9ca3af;
          font-size: 14px;
        }

        .image-placeholder.error {
          background: #fef2f2;
          color: #dc2626;
        }

        .loading-spinner {
          width: 32px;
          height: 32px;
          border: 3px solid #e5e7eb;
          border-top: 3px solid #3b82f6;
          border-radius: 50%;
          animation: spin 1s linear infinite;
          margin-bottom: 8px;
        }

        @keyframes spin {
          to {
            transform: rotate(360deg);
          }
        }

        .error-icon {
          width: 32px;
          height: 32px;
          margin-bottom: 8px;
        }

        .card-image {
          width: 100%;
          height: 100%;
          object-fit: cover;
          opacity: 0;
          transition: opacity 0.3s;
        }

        .card-image.loaded {
          opacity: 1;
        }

        .score-badge {
          position: absolute;
          top: 8px;
          right: 8px;
          background: rgba(0, 0, 0, 0.8);
          color: white;
          padding: 4px 8px;
          border-radius: 12px;
          font-size: 12px;
          font-weight: 600;
        }

        .card-content {
          padding: 16px;
        }

        .style-description {
          font-size: 16px;
          font-weight: 600;
          color: #374151;
          margin: 0 0 12px 0;
          line-height: 1.4;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }

        .categories {
          display: flex;
          flex-wrap: wrap;
          gap: 6px;
          margin-bottom: 12px;
        }

        .category-tag {
          padding: 4px 8px;
          background: #eff6ff;
          color: #1d4ed8;
          border-radius: 12px;
          font-size: 12px;
          font-weight: 500;
        }

        .color-palette {
          margin-bottom: 12px;
        }

        .palette-label {
          font-size: 12px;
          font-weight: 500;
          color: #6b7280;
          display: block;
          margin-bottom: 6px;
        }

        .color-swatches {
          display: flex;
          gap: 4px;
        }

        .color-swatch {
          width: 20px;
          height: 20px;
          border-radius: 4px;
          border: 1px solid #e5e7eb;
          cursor: pointer;
        }

        .design-styles {
          display: flex;
          flex-wrap: wrap;
          gap: 6px;
          margin-bottom: 12px;
        }

        .style-tag {
          padding: 4px 8px;
          background: #f3f4f6;
          color: #374151;
          border-radius: 12px;
          font-size: 12px;
          font-weight: 500;
        }

        .environment-tags {
          display: flex;
          align-items: center;
          gap: 8px;
        }

        .env-label {
          font-size: 12px;
          font-weight: 500;
          color: #6b7280;
        }

        .env-tags {
          display: flex;
          gap: 4px;
        }

        .env-tag {
          padding: 2px 6px;
          background: #ecfdf5;
          color: #065f46;
          border-radius: 8px;
          font-size: 11px;
          font-weight: 500;
        }

        .env-tag.more {
          background: #f3f4f6;
          color: #6b7280;
        }
      `}</style>
    </div>
  );
};

export default OutfitCard;
