/**
 * 素材检索管理 Hook
 * 提供基于收藏方案的素材检索功能，包含缓存和防抖优化
 */

import { useState, useCallback, useRef, useEffect } from 'react';
import { OutfitFavorite, CompareOutfitFavoritesResponse } from '../types/outfitFavorite';
import { MaterialSearchResponse } from '../types/materialSearch';
import { OutfitFavoriteService } from '../services/outfitFavoriteService';

interface UseMaterialSearchOptions {
  /** 防抖延迟(毫秒) */
  debounceDelay?: number;
  /** 缓存时间(毫秒) */
  cacheTime?: number;
}

interface MaterialSearchState {
  /** 是否正在检索 */
  isSearching: boolean;
  /** 是否正在对比 */
  isComparing: boolean;
  /** 错误信息 */
  error?: string;
}

interface SearchCacheItem {
  data: MaterialSearchResponse;
  timestamp: number;
  favoriteId: string;
  page: number;
  pageSize: number;
}

interface ComparisonCacheItem {
  data: CompareOutfitFavoritesResponse;
  timestamp: number;
  favoriteId1: string;
  favoriteId2: string;
}

interface UseMaterialSearchReturn {
  /** 检索状态 */
  state: MaterialSearchState;
  /** 基于收藏方案检索素材 */
  searchByFavorite: (
    favorite: OutfitFavorite,
    page?: number,
    pageSize?: number
  ) => Promise<MaterialSearchResponse | null>;
  /** 对比两个收藏方案 */
  compareFavorites: (
    favorite1: OutfitFavorite,
    favorite2: OutfitFavorite,
    page?: number,
    pageSize?: number
  ) => Promise<CompareOutfitFavoritesResponse | null>;
  /** 清除缓存 */
  clearCache: () => void;
}

/**
 * 素材检索管理 Hook
 */
export const useMaterialSearch = (
  options: UseMaterialSearchOptions = {}
): UseMaterialSearchReturn => {
  const { debounceDelay = 300, cacheTime = 3 * 60 * 1000 } = options; // 默认缓存3分钟

  const [state, setState] = useState<MaterialSearchState>({
    isSearching: false,
    isComparing: false,
  });

  // 缓存
  const searchCacheRef = useRef<Map<string, SearchCacheItem>>(new Map());
  const comparisonCacheRef = useRef<Map<string, ComparisonCacheItem>>(new Map());

  // 防抖定时器
  const debounceTimerRef = useRef<NodeJS.Timeout>();

  // 生成搜索缓存键
  const getSearchCacheKey = useCallback((favoriteId: string, page: number, pageSize: number) => {
    return `${favoriteId}-${page}-${pageSize}`;
  }, []);

  // 生成对比缓存键
  const getComparisonCacheKey = useCallback((favoriteId1: string, favoriteId2: string) => {
    return `${favoriteId1}-${favoriteId2}`;
  }, []);

  // 检查搜索缓存是否有效
  const isSearchCacheValid = useCallback((cacheItem: SearchCacheItem) => {
    return Date.now() - cacheItem.timestamp < cacheTime;
  }, [cacheTime]);

  // 检查对比缓存是否有效
  const isComparisonCacheValid = useCallback((cacheItem: ComparisonCacheItem) => {
    return Date.now() - cacheItem.timestamp < cacheTime;
  }, [cacheTime]);

  // 清除过期缓存
  const clearExpiredCache = useCallback(() => {
    const now = Date.now();

    // 清除过期的搜索缓存
    for (const [key, item] of searchCacheRef.current.entries()) {
      if (now - item.timestamp >= cacheTime) {
        searchCacheRef.current.delete(key);
      }
    }

    // 清除过期的对比缓存
    for (const [key, item] of comparisonCacheRef.current.entries()) {
      if (now - item.timestamp >= cacheTime) {
        comparisonCacheRef.current.delete(key);
      }
    }
  }, [cacheTime]);

  // 基于收藏方案检索素材
  const searchByFavorite = useCallback(async (
    favorite: OutfitFavorite,
    page: number = 1,
    pageSize: number = 9
  ): Promise<MaterialSearchResponse | null> => {
    const cacheKey = getSearchCacheKey(favorite.id, page, pageSize);
    
    // 检查缓存
    const cachedItem = searchCacheRef.current.get(cacheKey);
    if (cachedItem && isSearchCacheValid(cachedItem)) {
      return cachedItem.data;
    }

    // 清除之前的防抖定时器
    if (debounceTimerRef.current) {
      clearTimeout(debounceTimerRef.current);
    }

    return new Promise((resolve) => {
      debounceTimerRef.current = setTimeout(async () => {
        setState(prev => ({ ...prev, isSearching: true, error: undefined }));

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

          // 更新缓存
          searchCacheRef.current.set(cacheKey, {
            data: response,
            timestamp: Date.now(),
            favoriteId: favorite.id,
            page,
            pageSize,
          });

          // 清除过期缓存
          clearExpiredCache();

          resolve(response);
        } catch (error) {
          console.error('素材检索失败:', error);
          setState(prev => ({ 
            ...prev, 
            error: error instanceof Error ? error.message : '素材检索失败' 
          }));
          resolve(null);
        } finally {
          setState(prev => ({ ...prev, isSearching: false }));
        }
      }, debounceDelay);
    });
  }, [getSearchCacheKey, isSearchCacheValid, debounceDelay, clearExpiredCache]);

  // 对比两个收藏方案
  const compareFavorites = useCallback(async (
    favorite1: OutfitFavorite,
    favorite2: OutfitFavorite,
    page: number = 1,
    pageSize: number = 9
  ): Promise<CompareOutfitFavoritesResponse | null> => {
    const cacheKey = getComparisonCacheKey(favorite1.id, favorite2.id);
    
    // 检查缓存
    const cachedItem = comparisonCacheRef.current.get(cacheKey);
    if (cachedItem && isComparisonCacheValid(cachedItem)) {
      return cachedItem.data;
    }

    setState(prev => ({ ...prev, isComparing: true, error: undefined }));

    try {
      const response = await OutfitFavoriteService.compareOutfitFavorites(
        favorite1.id,
        favorite2.id,
        page,
        pageSize
      );

      // 更新缓存
      comparisonCacheRef.current.set(cacheKey, {
        data: response,
        timestamp: Date.now(),
        favoriteId1: favorite1.id,
        favoriteId2: favorite2.id,
      });

      // 清除过期缓存
      clearExpiredCache();

      return response;
    } catch (error) {
      console.error('方案对比失败:', error);
      setState(prev => ({ 
        ...prev, 
        error: error instanceof Error ? error.message : '方案对比失败' 
      }));
      return null;
    } finally {
      setState(prev => ({ ...prev, isComparing: false }));
    }
  }, [getComparisonCacheKey, isComparisonCacheValid, clearExpiredCache]);

  // 清除所有缓存
  const clearCache = useCallback(() => {
    searchCacheRef.current.clear();
    comparisonCacheRef.current.clear();
  }, []);

  // 组件卸载时清理定时器
  useEffect(() => {
    return () => {
      if (debounceTimerRef.current) {
        clearTimeout(debounceTimerRef.current);
      }
    };
  }, []);

  // 定期清理过期缓存
  useEffect(() => {
    const interval = setInterval(clearExpiredCache, cacheTime);
    return () => clearInterval(interval);
  }, [clearExpiredCache, cacheTime]);

  return {
    state,
    searchByFavorite,
    compareFavorites,
    clearCache,
  };
};

export default useMaterialSearch;
