import React, { useState, useCallback, useRef, useEffect } from 'react';
import { Search, Heart, Grid, RefreshCw, Filter, RotateCcw } from 'lucide-react';
import { OutfitFavorite } from '../../types/outfitFavorite';
import { MaterialSearchResponse } from '../../types/materialSearch';
import { OutfitFavoriteService } from '../../services/outfitFavoriteService';
import FavoriteSelector from '../../components/outfit/FavoriteSelector';

/**
 * 素材检索工具
 * 支持基于收藏方案的智能素材检索
 */
const MaterialSearchTool: React.FC = () => {
  const [selectedFavorite, setSelectedFavorite] = useState<OutfitFavorite | null>(null);
  const [searchResults, setSearchResults] = useState<MaterialSearchResponse | null>(null);
  const [isSearching, setIsSearching] = useState(false);
  const [searchError, setSearchError] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(9);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [hasMoreData, setHasMoreData] = useState(true);
  const scrollContainerRef = useRef<HTMLDivElement>(null);

  // 执行检索
  const handleSearch = useCallback(async (page: number = 1, favorite?: OutfitFavorite | null, isLoadMore: boolean = false) => {
    const targetFavorite = favorite || selectedFavorite;
    if (!targetFavorite) return;

    if (isLoadMore) {
      setIsLoadingMore(true);
    } else {
      setIsSearching(true);
    }
    setSearchError(null);
    setCurrentPage(page);

    try {
      const response = await OutfitFavoriteService.searchMaterialsByFavorite(
        targetFavorite.id,
        page,
        pageSize
      );

      if (isLoadMore && searchResults) {
        // 加载更多：合并结果
        setSearchResults({
          ...response,
          results: [...searchResults.results, ...response.results]
        });
      } else {
        // 新搜索：替换结果
        setSearchResults(response);
      }

      // 检查是否还有更多数据
      setHasMoreData(page < response.total_pages);
    } catch (error) {
      console.error('素材检索失败:', error);
      setSearchError(error instanceof Error ? error.message : '素材检索失败');
    } finally {
      setIsSearching(false);
      setIsLoadingMore(false);
    }
  }, [selectedFavorite, pageSize, searchResults]);

  // 处理收藏方案选择
  const handleFavoriteSelect = useCallback((favorite: OutfitFavorite | null) => {
    setSelectedFavorite(favorite);
    setSearchResults(null);
    setSearchError(null);
    setCurrentPage(1);

    // 如果选择了方案，自动执行检索
    if (favorite) {
      // 直接传递favorite参数，避免状态更新延迟问题
      handleSearch(1, favorite);
    }
  }, [handleSearch]);



  // 加载更多
  const handleLoadMore = useCallback(() => {
    if (!isLoadingMore && hasMoreData && searchResults) {
      const nextPage = currentPage + 1;
      handleSearch(nextPage, selectedFavorite, true);
    }
  }, [isLoadingMore, hasMoreData, searchResults, currentPage, handleSearch, selectedFavorite]);

  // 刷新数据
  const handleRefresh = useCallback(async () => {
    if (!selectedFavorite || isRefreshing) return;

    setIsRefreshing(true);
    setCurrentPage(1);
    setHasMoreData(true);

    try {
      await handleSearch(1, selectedFavorite, false);
    } finally {
      setIsRefreshing(false);
    }
  }, [selectedFavorite, isRefreshing, handleSearch]);

  // 滚动监听，实现无限滚动
  useEffect(() => {
    const container = scrollContainerRef.current;
    if (!container) return;

    const handleScroll = () => {
      const { scrollTop, scrollHeight, clientHeight } = container;
      const isNearBottom = scrollTop + clientHeight >= scrollHeight - 100; // 提前100px触发

      if (isNearBottom && hasMoreData && !isLoadingMore && !isSearching) {
        handleLoadMore();
      }
    };

    container.addEventListener('scroll', handleScroll);
    return () => container.removeEventListener('scroll', handleScroll);
  }, [hasMoreData, isLoadingMore, isSearching, handleLoadMore]);

  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-green-500 to-blue-600 rounded-xl flex items-center justify-center shadow-lg">
            <Search className="w-6 h-6 text-white" />
          </div>
          <div>
            <h1 className="text-3xl font-bold bg-gradient-to-r from-gray-900 to-green-600 bg-clip-text text-transparent">
              素材检索
            </h1>
            <p className="text-gray-600 text-lg">基于收藏方案的智能素材检索</p>
          </div>
        </div>
      </div>

      {/* 主要内容区域 */}
      <div className="flex-1 flex gap-6 min-h-0">
        {/* 左侧：检索结果展示区域 (70%) */}
        <div className="flex-1 flex flex-col min-h-0">
          <div className="card p-6 flex-1 flex flex-col">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-xl font-semibold text-gray-900">检索结果</h2>
              <div className="flex items-center gap-3">
                {/* 刷新按钮 */}
                {selectedFavorite && (
                  <button
                    onClick={handleRefresh}
                    disabled={isRefreshing || isSearching}
                    className="p-2 text-gray-500 hover:text-primary-600 rounded-lg hover:bg-primary-50 transition-colors disabled:opacity-50"
                    title="刷新数据"
                  >
                    <RotateCcw className={`w-4 h-4 ${isRefreshing ? 'animate-spin' : ''}`} />
                  </button>
                )}

                {/* 状态指示器 */}
                {isSearching && (
                  <div className="flex items-center gap-2 text-primary-600">
                    <RefreshCw className="w-4 h-4 animate-spin" />
                    <span className="text-sm">检索中...</span>
                  </div>
                )}
                {isRefreshing && (
                  <div className="flex items-center gap-2 text-blue-600">
                    <RotateCcw className="w-4 h-4 animate-spin" />
                    <span className="text-sm">刷新中...</span>
                  </div>
                )}

                {/* 结果统计 */}
                {searchResults && (
                  <span className="text-sm text-gray-500">
                    已显示 {searchResults.results.length} / {searchResults.total_size} 个结果
                    {searchResults.search_time_ms && (
                      <span className="ml-2">({searchResults.search_time_ms}ms)</span>
                    )}
                  </span>
                )}
              </div>
            </div>

            {/* 检索错误显示 */}
            {searchError && (
              <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg">
                <p className="text-red-600 text-sm">{searchError}</p>
              </div>
            )}

            {/* 检索结果网格 */}
            <div ref={scrollContainerRef} className="flex-1 overflow-y-auto">
              {!selectedFavorite ? (
                <div className="flex-1 flex items-center justify-center">
                  <div className="text-center">
                    <Heart className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                    <p className="text-gray-500 text-lg mb-2">选择收藏方案开始检索</p>
                    <p className="text-sm text-gray-400">从右侧选择一个收藏的穿搭方案</p>
                  </div>
                </div>
              ) : searchResults && searchResults.results.length > 0 ? (
                <div className="space-y-4">
                  <div className="grid grid-cols-3 gap-4">
                    {searchResults.results.map((result, index) => (
                      <div key={result.id || index} className="card p-4 hover:shadow-lg transition-shadow">
                        <img
                          src={result.image_url}
                          alt="Material"
                          className="w-full h-48 object-cover rounded-lg mb-3"
                          onError={(e) => {
                            e.currentTarget.src = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgdmlld0JveD0iMCAwIDIwMCAyMDAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIyMDAiIGhlaWdodD0iMjAwIiBmaWxsPSIjRjNGNEY2Ii8+CjxwYXRoIGQ9Ik0xMDAgNzBMMTMwIDEwMEgxMTBWMTMwSDkwVjEwMEg3MEwxMDAgNzBaIiBmaWxsPSIjOUI5QkEwIi8+Cjx0ZXh0IHg9IjEwMCIgeT0iMTUwIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBmaWxsPSIjOUI5QkEwIiBmb250LXNpemU9IjEyIj7lm77niYfliKDpmaTlpLHotKU8L3RleHQ+Cjwvc3ZnPg==';
                          }}
                        />
                        <div className="space-y-2">
                          <p className="text-sm text-gray-600 line-clamp-2">
                            {result.style_description}
                          </p>
                          <div className="flex flex-wrap gap-1">
                            {result.environment_tags?.slice(0, 3).map((tag, i) => (
                              <span key={i} className="px-2 py-1 bg-gray-100 text-xs rounded-full">
                                {tag}
                              </span>
                            ))}
                          </div>
                          {result.relevance_score && (
                            <div className="text-xs text-gray-500">
                              相关度: {(result.relevance_score * 100).toFixed(1)}%
                            </div>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>

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

                  {/* 没有更多数据提示 */}
                  {!hasMoreData && searchResults.results.length > 0 && (
                    <div className="text-center py-6 text-gray-500 text-sm border-t border-gray-200">
                      已显示全部 {searchResults.total_size} 个结果
                    </div>
                  )}

                  {/* 手动加载更多按钮（备用） */}
                  {hasMoreData && !isLoadingMore && searchResults.results.length > 0 && (
                    <div className="text-center py-4">
                      <button
                        onClick={handleLoadMore}
                        className="px-6 py-2 text-primary-600 border border-primary-300 rounded-lg hover:bg-primary-50 transition-colors"
                      >
                        加载更多
                      </button>
                    </div>
                  )}
                </div>
              ) : selectedFavorite && !isSearching ? (
                <div className="flex-1 flex items-center justify-center">
                  <div className="text-center">
                    <Grid className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                    <p className="text-gray-500">没有找到相关素材</p>
                    <p className="text-sm text-gray-400 mt-2">尝试选择其他收藏方案</p>
                  </div>
                </div>
              ) : null}
            </div>
          </div>
        </div>

        {/* 右侧：收藏方案选择面板 (30%) */}
        <div className="w-96 flex flex-col space-y-4">
          {/* 收藏方案选择 */}
          <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-4" style={{ overflow: 'visible' }}>
            <h3 className="text-lg font-semibold mb-3">选择收藏方案</h3>
            <FavoriteSelector
              selectedFavorite={selectedFavorite}
              onSelectionChange={handleFavoriteSelect}
              placeholder="选择一个收藏方案..."
              className="mb-4"
            />

            {selectedFavorite && (
              <div className="mt-4 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                <h4 className="text-sm font-medium text-blue-800 mb-2">当前方案</h4>
                <div className="space-y-2 text-sm text-blue-700">
                  <p><strong>名称:</strong> {OutfitFavoriteService.getDisplayName(selectedFavorite)}</p>
                  <p><strong>描述:</strong> {OutfitFavoriteService.getDescription(selectedFavorite)}</p>
                  <div>
                    <strong>风格标签:</strong>
                    <div className="flex flex-wrap gap-1 mt-1">
                      {OutfitFavoriteService.getStyleTags(selectedFavorite).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>
            )}
          </div>

          {/* 检索操作 */}
          {selectedFavorite && (
            <div className="card p-4">
              <h3 className="text-lg font-semibold mb-3">检索操作</h3>
              <div className="space-y-3">
                <button
                  onClick={() => handleSearch(1)}
                  disabled={isSearching}
                  className="w-full btn-primary flex items-center justify-center gap-2"
                >
                  {isSearching ? (
                    <RefreshCw className="w-4 h-4 animate-spin" />
                  ) : (
                    <Search className="w-4 h-4" />
                  )}
                  {isSearching ? '检索中...' : '重新检索'}
                </button>

                <button
                  onClick={() => setSelectedFavorite(null)}
                  className="w-full btn-secondary flex items-center justify-center gap-2"
                >
                  <Filter className="w-4 h-4" />
                  清除选择
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default MaterialSearchTool;
