import React, { useState, useEffect, useCallback } from 'react';
import { ArrowLeftRight, Heart, Plus } from 'lucide-react';
import { OutfitFavorite } from '../../types/outfitFavorite';
import { OutfitFavoriteService } from '../../services/outfitFavoriteService';
import OutfitComparisonView from '../../components/outfit/OutfitComparisonView';

/**
 * 穿搭方案对比工具
 * 支持选择两个收藏方案进行分屏对比
 */
const OutfitComparisonTool: React.FC = () => {
  const [favorites, setFavorites] = useState<OutfitFavorite[]>([]);
  const [selectedFavorite1, setSelectedFavorite1] = useState<OutfitFavorite | null>(null);
  const [selectedFavorite2, setSelectedFavorite2] = useState<OutfitFavorite | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isTemporary, setIsTemporary] = useState(false);

  // 加载收藏列表
  const loadFavorites = useCallback(async () => {
    setIsLoading(true);
    setError(null);

    try {
      const response = await OutfitFavoriteService.getFavoriteOutfits();
      setFavorites(response.favorites);
    } catch (err) {
      console.error('加载收藏列表失败:', err);
      setError(err instanceof Error ? err.message : '加载收藏列表失败');
    } finally {
      setIsLoading(false);
    }
  }, []);

  // 初始加载
  useEffect(() => {
    loadFavorites();

    // 检查是否有从推荐页面传来的对比数据
    try {
      const comparisonData = localStorage.getItem('outfit-comparison-data');
      if (comparisonData) {
        const data = JSON.parse(comparisonData);
        if (data.leftFavorite && data.rightFavorite) {
          // 将推荐数据转换为收藏格式
          const leftFavorite: OutfitFavorite = {
            id: data.leftFavorite.id,
            recommendation_data: data.leftFavorite.recommendation_data,
            custom_name: data.leftFavorite.custom_name,
            created_at: data.leftFavorite.created_at
          };

          const rightFavorite: OutfitFavorite = {
            id: data.rightFavorite.id,
            recommendation_data: data.rightFavorite.recommendation_data,
            custom_name: data.rightFavorite.custom_name,
            created_at: data.rightFavorite.created_at
          };

          setSelectedFavorite1(leftFavorite);
          setSelectedFavorite2(rightFavorite);
          setIsTemporary(true);

          // 清除临时数据
          localStorage.removeItem('outfit-comparison-data');
        }
      }
    } catch (error) {
      console.warn('读取对比数据失败:', error);
    }
  }, [loadFavorites]);

  // 重置选择
  const handleReset = useCallback(() => {
    setSelectedFavorite1(null);
    setSelectedFavorite2(null);
  }, []);

  // 渲染收藏选择器
  const renderFavoriteSelector = (
    title: string,
    selectedFavorite: OutfitFavorite | null,
    onSelect: (favorite: OutfitFavorite) => void,
    excludeId?: string
  ) => {
    const availableFavorites = favorites.filter(f => f.id !== excludeId);

    return (
      <div className="bg-white rounded-2xl border border-gray-100 shadow-sm hover:shadow-lg hover:shadow-primary-500/10 transition-all duration-300 p-6" style={{ overflow: 'visible' }}>
        <h3 className="text-lg font-semibold text-gray-900 mb-4">{title}</h3>
        
        {selectedFavorite ? (
          <div className="space-y-4">
            {/* 已选择的方案 */}
            <div className="bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg p-4 border border-blue-200">
              <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">
                  <h4 className="text-md font-semibold text-gray-900 mb-1">
                    {OutfitFavoriteService.getDisplayName(selectedFavorite)}
                  </h4>
                  <p className="text-gray-600 text-sm mb-2 line-clamp-2">
                    {OutfitFavoriteService.getDescription(selectedFavorite)}
                  </p>
                  <div className="flex flex-wrap gap-1">
                    {OutfitFavoriteService.getStyleTags(selectedFavorite).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>
                    ))}
                  </div>
                </div>
              </div>
            </div>
            
            {/* 重新选择按钮 */}
            <button
              onClick={() => onSelect(null as any)}
              className="w-full px-4 py-2 text-blue-600 border border-blue-300 rounded-lg hover:bg-blue-50 transition-colors"
            >
              重新选择
            </button>
          </div>
        ) : (
          <div className="space-y-3">
            {availableFavorites.length === 0 ? (
              <div className="text-center py-8">
                <Heart className="w-12 h-12 text-gray-300 mx-auto mb-3" />
                <p className="text-gray-500">没有可选择的收藏方案</p>
              </div>
            ) : (
              availableFavorites.map((favorite) => (
                <button
                  key={favorite.id}
                  onClick={() => onSelect(favorite)}
                  className="w-full text-left p-3 border border-gray-200 rounded-lg hover:border-blue-300 hover:bg-blue-50 transition-all"
                >
                  <div className="flex items-start gap-3">
                    <div className="w-8 h-8 bg-gradient-to-br from-red-500 to-pink-600 rounded-lg flex items-center justify-center shadow-sm flex-shrink-0">
                      <Heart className="w-4 h-4 text-white fill-current" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <h4 className="text-sm font-medium text-gray-900 mb-1 truncate">
                        {OutfitFavoriteService.getDisplayName(favorite)}
                      </h4>
                      <p className="text-gray-600 text-xs line-clamp-1">
                        {OutfitFavoriteService.getDescription(favorite)}
                      </p>
                    </div>
                  </div>
                </button>
              ))
            )}
          </div>
        )}
      </div>
    );
  };

  // 如果两个方案都已选择，显示对比视图
  if (selectedFavorite1 && selectedFavorite2) {
    return (
      <div className="h-full flex flex-col">
        {/* 页面标题 */}
        <div className="page-header flex items-center justify-between mb-6">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 bg-gradient-to-br from-blue-500 to-purple-600 rounded-xl flex items-center justify-center shadow-lg">
              <ArrowLeftRight className="w-6 h-6 text-white" />
            </div>
            <div>
              <h1 className="text-3xl font-bold bg-gradient-to-r from-gray-900 to-blue-600 bg-clip-text text-transparent">
                方案对比
              </h1>
              <p className="text-gray-600 text-lg">对比两个收藏方案的素材检索结果</p>
            </div>
          </div>
          <button
            onClick={handleReset}
            className="px-4 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
          >
            重新选择
          </button>
        </div>

        {/* 对比视图 */}
        <div className="flex-1 min-h-0">
          <OutfitComparisonView
            favorite1={selectedFavorite1}
            favorite2={selectedFavorite2}
            isTemporary={isTemporary}
            className="h-full"
          />
        </div>
      </div>
    );
  }

  return (
    <div className="h-full flex flex-col">
      {/* 页面标题 */}
      <div className="page-header flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <div className="w-12 h-12 bg-gradient-to-br from-blue-500 to-purple-600 rounded-xl flex items-center justify-center shadow-lg">
            <ArrowLeftRight className="w-6 h-6 text-white" />
          </div>
          <div>
            <h1 className="text-3xl font-bold bg-gradient-to-r from-gray-900 to-blue-600 bg-clip-text text-transparent">
              方案对比
            </h1>
            <p className="text-gray-600 text-lg">选择两个收藏方案进行对比分析</p>
          </div>
        </div>
      </div>

      {/* 选择界面 */}
      <div className="flex-1">
        {isLoading ? (
          <div className="flex items-center justify-center h-64">
            <div className="text-center">
              <div className="w-8 h-8 border-4 border-primary-500 border-t-transparent rounded-full animate-spin mx-auto mb-3"></div>
              <p className="text-gray-600">加载收藏列表...</p>
            </div>
          </div>
        ) : error ? (
          <div className="text-center py-12">
            <p className="text-red-600 mb-4">{error}</p>
            <button
              onClick={loadFavorites}
              className="px-4 py-2 bg-primary-500 text-white rounded-lg hover:bg-primary-600 transition-colors"
            >
              重新加载
            </button>
          </div>
        ) : favorites.length < 2 ? (
          <div className="text-center py-12">
            <ArrowLeftRight className="w-16 h-16 text-gray-300 mx-auto mb-4" />
            <h3 className="text-lg font-semibold text-gray-900 mb-2">需要至少两个收藏方案</h3>
            <p className="text-gray-500 mb-6">请先收藏一些穿搭方案，然后再进行对比</p>
            <button
              onClick={() => window.location.href = '/tools/outfit-recommendation'}
              className="px-6 py-3 bg-primary-500 text-white rounded-lg hover:bg-primary-600 transition-colors inline-flex items-center gap-2"
            >
              <Plus className="w-5 h-5" />
              去收藏方案
            </button>
          </div>
        ) : (
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* 方案1选择器 */}
            {renderFavoriteSelector(
              '选择第一个方案',
              selectedFavorite1,
              setSelectedFavorite1,
              selectedFavorite2?.id
            )}

            {/* 方案2选择器 */}
            {renderFavoriteSelector(
              '选择第二个方案',
              selectedFavorite2,
              setSelectedFavorite2,
              selectedFavorite1?.id
            )}
          </div>
        )}
      </div>
    </div>
  );
};

export default OutfitComparisonTool;
