import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Heart, Search, Loader2, ArrowLeftRight, X, RefreshCw, RotateCcw } from 'lucide-react';
import { OutfitFavorite, CompareOutfitFavoritesResponse } from '../../types/outfitFavorite';
import { OutfitFavoriteService } from '../../services/outfitFavoriteService';

interface OutfitComparisonViewProps {
  /** 第一个收藏方案 */
  favorite1: OutfitFavorite;
  /** 第二个收藏方案 */
  favorite2: OutfitFavorite;
  /** 关闭对比回调 */
  onClose?: () => void;
  /** 是否为临时对比（来自推荐页面） */
  isTemporary?: boolean;
  /** 自定义类名 */
  className?: string;
}

/**
 * 穿搭方案对比视图组件
 * 提供分屏对比两个收藏方案的素材检索结果
 */
export const OutfitComparisonView: React.FC<OutfitComparisonViewProps> = ({
  favorite1,
  favorite2,
  onClose,
  isTemporary = false,
  className = '',
}) => {
  const [comparisonData, setComparisonData] = useState<CompareOutfitFavoritesResponse | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 执行对比
  const performComparison = useCallback(async () => {
    setIsLoading(true);
    setError(null);

    try {
      if (isTemporary) {
        // 临时对比：需要先将推荐数据保存为临时收藏，然后执行对比
        try {
          // 保存第一个方案为临时收藏
          const saveResponse1 = await OutfitFavoriteService.saveToFavorites(
            favorite1.recommendation_data,
            `临时对比-${favorite1.custom_name || favorite1.recommendation_data.title}`
          );

          // 保存第二个方案为临时收藏
          const saveResponse2 = await OutfitFavoriteService.saveToFavorites(
            favorite2.recommendation_data,
            `临时对比-${favorite2.custom_name || favorite2.recommendation_data.title}`
          );

          // 使用临时收藏的ID执行对比
          const response = await OutfitFavoriteService.compareOutfitFavorites(
            saveResponse1.favorite.id,
            saveResponse2.favorite.id
          );

          // 更新返回的收藏信息，使用原始的自定义名称
          response.favorite_1.custom_name = favorite1.custom_name || favorite1.recommendation_data.title;
          response.favorite_2.custom_name = favorite2.custom_name || favorite2.recommendation_data.title;

          setComparisonData(response);

          // 清理临时收藏（可选，或者可以在组件卸载时清理）
          // 这里暂时保留，让用户可以看到完整的对比结果
        } catch (tempError) {
          console.error('临时对比失败:', tempError);
          throw tempError;
        }
      } else {
        // 正常对比：调用后端API
        const response = await OutfitFavoriteService.compareOutfitFavorites(
          favorite1.id,
          favorite2.id
        );
        setComparisonData(response);
      }
    } catch (err) {
      console.error('对比失败:', err);
      setError(err instanceof Error ? err.message : '对比失败');
    } finally {
      setIsLoading(false);
    }
  }, [favorite1, favorite2, isTemporary]);

  // 初始加载
  useEffect(() => {
    performComparison();
  }, [performComparison]);

  // 渲染方案信息卡片
  const renderFavoriteCard = (favorite: OutfitFavorite, _side: 'left' | 'right') => {
    const displayName = OutfitFavoriteService.getDisplayName(favorite);
    const description = OutfitFavoriteService.getDescription(favorite);
    const styleTags = OutfitFavoriteService.getStyleTags(favorite);
    const occasions = OutfitFavoriteService.getOccasions(favorite);

    return (
      <div className="bg-white rounded-lg border border-gray-200 p-4 mb-4">
        <div className="flex items-start gap-3">
          <div className="w-10 h-10 bg-gradient-to-br from-red-500 to-pink-600 rounded-lg flex items-center justify-center shadow-md flex-shrink-0">
            <Heart className="w-5 h-5 text-white fill-current" />
          </div>
          <div className="flex-1 min-w-0">
            <h3 className="text-lg font-semibold text-gray-900 mb-1 truncate">
              {displayName}
            </h3>
            <p className="text-gray-600 text-sm mb-2 line-clamp-2">
              {description}
            </p>
            <div className="flex flex-wrap gap-1">
              {styleTags.slice(0, 2).map((tag, index) => (
                <span
                  key={index}
                  className="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full"
                >
                  {tag}
                </span>
              ))}
              {occasions.slice(0, 1).map((occasion, index) => (
                <span
                  key={index}
                  className="px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full"
                >
                  {occasion}
                </span>
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  };

  // 渲染素材网格
  const renderMaterialGrid = (materials: any[], _side: 'left' | 'right') => {
    if (materials.length === 0) {
      return (
        <div className="flex items-center justify-center py-12">
          <div className="text-center">
            <Search className="w-12 h-12 text-gray-300 mx-auto mb-3" />
            <p className="text-gray-500">没有找到相关素材</p>
          </div>
        </div>
      );
    }

    return (
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {materials.map((material, index) => (
          <div key={material.id || index} className="bg-white rounded-lg border border-gray-200 p-3 hover:shadow-md transition-shadow">
            <img
              src={material.image_url}
              alt="Material"
              className="w-full h-32 object-cover rounded-lg mb-2"
              onError={(e) => {
                e.currentTarget.src = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgdmlld0JveD0iMCAwIDIwMCAyMDAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIyMDAiIGhlaWdodD0iMjAwIiBmaWxsPSIjRjNGNEY2Ii8+CjxwYXRoIGQ9Ik0xMDAgNzBMMTMwIDEwMEgxMTBWMTMwSDkwVjEwMEg3MEwxMDAgNzBaIiBmaWxsPSIjOUI5QkEwIi8+Cjx0ZXh0IHg9IjEwMCIgeT0iMTUwIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBmaWxsPSIjOUI5QkEwIiBmb250LXNpemU9IjEyIj7lm77niYfliKDpmaTlpLHotKU8L3RleHQ+Cjwvc3ZnPg==';
              }}
            />
            <div className="space-y-1">
              <p className="text-xs text-gray-600 line-clamp-2">
                {material.style_description}
              </p>
              <div className="flex flex-wrap gap-1">
                {material.environment_tags?.slice(0, 2).map((tag: string, i: number) => (
                  <span key={i} className="px-1.5 py-0.5 bg-gray-100 text-xs rounded">
                    {tag}
                  </span>
                ))}
              </div>
              {material.relevance_score && (
                <div className="text-xs text-gray-500">
                  相关度: {(material.relevance_score * 100).toFixed(1)}%
                </div>
              )}
            </div>
          </div>
        ))}
      </div>
    );
  };

  if (isLoading) {
    return (
      <div className={`h-full flex items-center justify-center ${className}`}>
        <div className="text-center">
          <Loader2 className="w-8 h-8 text-primary-500 animate-spin mx-auto mb-3" />
          <p className="text-gray-600">正在对比方案...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className={`h-full flex items-center justify-center ${className}`}>
        <div className="text-center">
          <p className="text-red-600 mb-4">{error}</p>
          <button
            onClick={performComparison}
            className="px-4 py-2 bg-primary-500 text-white rounded-lg hover:bg-primary-600 transition-colors"
          >
            重新对比
          </button>
        </div>
      </div>
    );
  }

  if (!comparisonData) {
    return null;
  }

  return (
    <div className={`h-full flex flex-col ${className}`}>
      {/* 标题栏 */}
      <div className="flex items-center justify-between p-4 border-b border-gray-200 bg-white">
        <div className="flex items-center gap-3">
          <div className="w-8 h-8 bg-gradient-to-br from-blue-500 to-purple-600 rounded-lg flex items-center justify-center">
            <ArrowLeftRight className="w-4 h-4 text-white" />
          </div>
          <div>
            <h2 className="text-lg font-semibold text-gray-900">方案对比</h2>
            {isTemporary && (
              <p className="text-xs text-blue-600">来自推荐页面的临时对比</p>
            )}
          </div>
        </div>
        {onClose && (
          <button
            onClick={onClose}
            className="p-2 text-gray-400 hover:text-gray-600 rounded-lg hover:bg-gray-100 transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        )}
      </div>

      {/* 对比内容 */}
      <div className="flex-1 flex min-h-0">
        {/* 左侧方案 */}
        <div className="flex-1 p-4 border-r border-gray-200">
          <div className="h-full flex flex-col">
            {renderFavoriteCard(comparisonData.favorite_1, 'left')}
            
            <div className="flex-1 min-h-0">
              <div className="flex items-center justify-between mb-3">
                <h3 className="text-sm font-medium text-gray-700">检索结果</h3>
                <span className="text-xs text-gray-500">
                  {comparisonData.materials_1.total_size} 个结果
                </span>
              </div>
              <div className="h-full overflow-y-auto">
                {renderMaterialGrid(comparisonData.materials_1.results, 'left')}
              </div>
            </div>
          </div>
        </div>

        {/* 右侧方案 */}
        <div className="flex-1 p-4">
          <div className="h-full flex flex-col">
            {renderFavoriteCard(comparisonData.favorite_2, 'right')}
            
            <div className="flex-1 min-h-0">
              <div className="flex items-center justify-between mb-3">
                <h3 className="text-sm font-medium text-gray-700">检索结果</h3>
                <span className="text-xs text-gray-500">
                  {comparisonData.materials_2.total_size} 个结果
                </span>
              </div>
              <div className="h-full overflow-y-auto">
                {renderMaterialGrid(comparisonData.materials_2.results, 'right')}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default OutfitComparisonView;
