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';
import ImageCard from '../ImageCard';
import { GroundingSource } from '../../types/ragGrounding';
import { save } from '@tauri-apps/plugin-dialog';
import { invoke } from '@tauri-apps/api/core';


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 [isLoadingMore1, setIsLoadingMore1] = useState(false);
  const [isLoadingMore2, setIsLoadingMore2] = useState(false);
  const [isRefreshing1, setIsRefreshing1] = useState(false);
  const [isRefreshing2, setIsRefreshing2] = useState(false);
  const [hasMoreData1, setHasMoreData1] = useState(true);
  const [hasMoreData2, setHasMoreData2] = useState(true);
  const [currentPage1, setCurrentPage1] = useState(1);
  const [currentPage2, setCurrentPage2] = useState(1);

  // 滚动容器引用
  const scrollContainer1Ref = useRef<HTMLDivElement>(null);
  const scrollContainer2Ref = useRef<HTMLDivElement>(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);

          // 设置分页状态
          setHasMoreData1(response.materials_1.current_page < response.materials_1.total_pages);
          setHasMoreData2(response.materials_2.current_page < response.materials_2.total_pages);
          setCurrentPage1(response.materials_1.current_page);
          setCurrentPage2(response.materials_2.current_page);

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

        // 设置分页状态
        setHasMoreData1(response.materials_1.current_page < response.materials_1.total_pages);
        setHasMoreData2(response.materials_2.current_page < response.materials_2.total_pages);
        setCurrentPage1(response.materials_1.current_page);
        setCurrentPage2(response.materials_2.current_page);
      }
    } catch (err) {
      console.error('对比失败:', err);
      setError(err instanceof Error ? err.message : '对比失败');
    } finally {
      setIsLoading(false);
    }
  }, [favorite1, favorite2, isTemporary]);

  // 加载更多素材 - 左侧
  const loadMoreMaterials1 = useCallback(async () => {
    if (!comparisonData || isLoadingMore1 || !hasMoreData1) return;

    setIsLoadingMore1(true);
    try {
      const nextPage = currentPage1 + 1;
      const response = await OutfitFavoriteService.searchMaterialsByFavorite(
        comparisonData.favorite_1.id,
        nextPage,
        9
      );

      setComparisonData(prev => prev ? {
        ...prev,
        materials_1: {
          ...response,
          results: [...prev.materials_1.results, ...response.results]
        }
      } : null);

      setCurrentPage1(nextPage);
      setHasMoreData1(nextPage < response.total_pages);
    } catch (error) {
      console.error('加载更多素材失败 (左侧):', error);
    } finally {
      setIsLoadingMore1(false);
    }
  }, [comparisonData, isLoadingMore1, hasMoreData1, currentPage1]);

  // 加载更多素材 - 右侧
  const loadMoreMaterials2 = useCallback(async () => {
    if (!comparisonData || isLoadingMore2 || !hasMoreData2) return;

    setIsLoadingMore2(true);
    try {
      const nextPage = currentPage2 + 1;
      const response = await OutfitFavoriteService.searchMaterialsByFavorite(
        comparisonData.favorite_2.id,
        nextPage,
        9
      );

      setComparisonData(prev => prev ? {
        ...prev,
        materials_2: {
          ...response,
          results: [...prev.materials_2.results, ...response.results]
        }
      } : null);

      setCurrentPage2(nextPage);
      setHasMoreData2(nextPage < response.total_pages);
    } catch (error) {
      console.error('加载更多素材失败 (右侧):', error);
    } finally {
      setIsLoadingMore2(false);
    }
  }, [comparisonData, isLoadingMore2, hasMoreData2, currentPage2]);

  // 刷新素材 - 左侧
  const refreshMaterials1 = useCallback(async () => {
    if (!comparisonData || isRefreshing1) return;

    setIsRefreshing1(true);
    try {
      const response = await OutfitFavoriteService.searchMaterialsByFavorite(
        comparisonData.favorite_1.id,
        1,
        9
      );

      setComparisonData(prev => prev ? {
        ...prev,
        materials_1: response
      } : null);

      setCurrentPage1(1);
      setHasMoreData1(1 < response.total_pages);
    } catch (error) {
      console.error('刷新素材失败 (左侧):', error);
    } finally {
      setIsRefreshing1(false);
    }
  }, [comparisonData, isRefreshing1]);

  // 刷新素材 - 右侧
  const refreshMaterials2 = useCallback(async () => {
    if (!comparisonData || isRefreshing2) return;

    setIsRefreshing2(true);
    try {
      const response = await OutfitFavoriteService.searchMaterialsByFavorite(
        comparisonData.favorite_2.id,
        1,
        9
      );

      setComparisonData(prev => prev ? {
        ...prev,
        materials_2: response
      } : null);

      setCurrentPage2(1);
      setHasMoreData2(1 < response.total_pages);
    } catch (error) {
      console.error('刷新素材失败 (右侧):', error);
    } finally {
      setIsRefreshing2(false);
    }
  }, [comparisonData, isRefreshing2]);

  // 滚动监听 - 左侧
  useEffect(() => {
    const container = scrollContainer1Ref.current;
    if (!container) return;

    const handleScroll = () => {
      const { scrollTop, scrollHeight, clientHeight } = container;
      const isNearBottom = scrollTop + clientHeight >= scrollHeight - 100;

      if (isNearBottom && hasMoreData1 && !isLoadingMore1 && !isLoading) {
        loadMoreMaterials1();
      }
    };

    container.addEventListener('scroll', handleScroll);
    return () => container.removeEventListener('scroll', handleScroll);
  }, [hasMoreData1, isLoadingMore1, isLoading, loadMoreMaterials1]);

  // 滚动监听 - 右侧
  useEffect(() => {
    const container = scrollContainer2Ref.current;
    if (!container) return;

    const handleScroll = () => {
      const { scrollTop, scrollHeight, clientHeight } = container;
      const isNearBottom = scrollTop + clientHeight >= scrollHeight - 100;

      if (isNearBottom && hasMoreData2 && !isLoadingMore2 && !isLoading) {
        loadMoreMaterials2();
      }
    };

    container.addEventListener('scroll', handleScroll);
    return () => container.removeEventListener('scroll', handleScroll);
  }, [hasMoreData2, isLoadingMore2, isLoading, loadMoreMaterials2]);

  // 将MaterialSearchResult转换为GroundingSource的适配器函数
  const convertToGroundingSource = useCallback((material: any): GroundingSource => {
    return {
      uri: material.image_url,
      title: material.style_description || '素材图片',
      content: {
        text: material.style_description || '',
        id: material.id,
        material_type: material.material_type,
        relevance_score: material.relevance_score,
        environment_tags: material.environment_tags || [],
        style_tags: material.style_tags || [],
        occasion_tags: material.occasion_tags || [],
        color_info: material.color_info,
        // 为ImageCard提供必要的显示信息
        description: material.style_description,
        models: [],
        categories: material.style_tags || [],
        environmentTags: material.environment_tags || [],
        releaseDate: new Date().toISOString()
      }
    };
  }, []);

  // 下载素材到本地
  const downloadMaterial = useCallback(async (source: GroundingSource, materialId: string) => {
    try {
      if (!source.uri) {
        console.error('图片URL不存在');
        return;
      }

      // 获取文件扩展名
      const url = new URL(source.uri);
      const pathname = url.pathname;
      const extension = pathname.split('.').pop() || 'jpg';

      // 打开保存对话框
      const filePath = await save({
        defaultPath: `material_${materialId}.${extension}`,
        filters: [
          {
            name: '图片文件',
            extensions: ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']
          }
        ]
      });

      if (!filePath) {
        // 用户取消了保存
        return;
      }

      // 使用Tauri命令下载文件
      await invoke('download_image_from_uri', {
        uri: source.uri,
        filePath: filePath
      });

      console.log('文件下载成功:', filePath);
    } catch (error) {
      console.error('下载文件失败:', error);
      // 可以添加错误提示
    }
  }, []);

  // 初始加载
  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>
    );
  };

  // 渲染素材网格 - 使用ImageCard组件
  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-3 gap-4">
        {materials.map((material, index) => {
          const groundingSource = convertToGroundingSource(material);
          return (
            <ImageCard
              key={material.id || index}
              source={groundingSource}
              showDetails={true}
              className="w-full"
              onViewLarge={(source) => {
                // 可以添加查看大图的逻辑
                if (source.uri) {
                  window.open(source.uri, '_blank', 'noopener,noreferrer');
                }
              }}
              onDownload={(source) => {
                downloadMaterial(source, material.id || `${index}`);
              }}
            />
          );
        })}
      </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>
                <div className="flex items-center gap-2">
                  {/* 刷新按钮 */}
                  <button
                    onClick={refreshMaterials1}
                    disabled={isRefreshing1 || isLoading}
                    className="p-1 text-gray-500 hover:text-primary-600 rounded hover:bg-primary-50 transition-colors disabled:opacity-50"
                    title="刷新数据"
                  >
                    <RotateCcw className={`w-4 h-4 ${isRefreshing1 ? 'animate-spin' : ''}`} />
                  </button>

                  <span className="text-xs text-gray-500">
                    已显示 {comparisonData.materials_1.results.length} / {comparisonData.materials_1.total_size} 个结果
                  </span>
                </div>
              </div>
              <div ref={scrollContainer1Ref} className="h-full overflow-y-auto">
                {renderMaterialGrid(comparisonData.materials_1.results, 'left')}

                {/* 加载更多指示器 */}
                {isLoadingMore1 && (
                  <div className="flex items-center justify-center py-4">
                    <RefreshCw className="w-4 h-4 text-primary-500 animate-spin mr-2" />
                    <span className="text-sm text-gray-600">加载更多...</span>
                  </div>
                )}

                {/* 没有更多数据提示 */}
                {!hasMoreData1 && comparisonData.materials_1.results.length > 0 && (
                  <div className="text-center py-4 text-gray-500 text-xs">
                    已显示全部结果
                  </div>
                )}

                {/* 手动加载更多按钮（备用） */}
                {hasMoreData1 && !isLoadingMore1 && comparisonData.materials_1.results.length > 0 && (
                  <div className="text-center py-4">
                    <button
                      onClick={loadMoreMaterials1}
                      className="px-4 py-2 text-sm text-primary-600 border border-primary-300 rounded-lg hover:bg-primary-50 transition-colors"
                    >
                      加载更多
                    </button>
                  </div>
                )}
              </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>
                <div className="flex items-center gap-2">
                  {/* 刷新按钮 */}
                  <button
                    onClick={refreshMaterials2}
                    disabled={isRefreshing2 || isLoading}
                    className="p-1 text-gray-500 hover:text-primary-600 rounded hover:bg-primary-50 transition-colors disabled:opacity-50"
                    title="刷新数据"
                  >
                    <RotateCcw className={`w-4 h-4 ${isRefreshing2 ? 'animate-spin' : ''}`} />
                  </button>

                  <span className="text-xs text-gray-500">
                    已显示 {comparisonData.materials_2.results.length} / {comparisonData.materials_2.total_size} 个结果
                  </span>
                </div>
              </div>
              <div ref={scrollContainer2Ref} className="h-full overflow-y-auto">
                {renderMaterialGrid(comparisonData.materials_2.results, 'right')}

                {/* 加载更多指示器 */}
                {isLoadingMore2 && (
                  <div className="flex items-center justify-center py-4">
                    <RefreshCw className="w-4 h-4 text-primary-500 animate-spin mr-2" />
                    <span className="text-sm text-gray-600">加载更多...</span>
                  </div>
                )}

                {/* 没有更多数据提示 */}
                {!hasMoreData2 && comparisonData.materials_2.results.length > 0 && (
                  <div className="text-center py-4 text-gray-500 text-xs">
                    已显示全部结果
                  </div>
                )}

                {/* 手动加载更多按钮（备用） */}
                {hasMoreData2 && !isLoadingMore2 && comparisonData.materials_2.results.length > 0 && (
                  <div className="text-center py-4">
                    <button
                      onClick={loadMoreMaterials2}
                      className="px-4 py-2 text-sm text-primary-600 border border-primary-300 rounded-lg hover:bg-primary-50 transition-colors"
                    >
                      加载更多
                    </button>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default OutfitComparisonView;
