/**
 * 穿搭方案收藏管理 Hook
 * 提供缓存和状态管理功能，优化性能
 */

import { useState, useEffect, useCallback, useRef } from 'react';
import { OutfitFavorite, FavoriteOperationState } from '../types/outfitFavorite';
import { OutfitRecommendation } from '../types/outfitRecommendation';
import { OutfitFavoriteService } from '../services/outfitFavoriteService';

interface UseOutfitFavoritesOptions {
  /** 是否自动加载 */
  autoLoad?: boolean;
  /** 缓存时间(毫秒) */
  cacheTime?: number;
}

interface UseOutfitFavoritesReturn {
  /** 收藏列表 */
  favorites: OutfitFavorite[];
  /** 操作状态 */
  state: FavoriteOperationState;
  /** 加载收藏列表 */
  loadFavorites: () => Promise<void>;
  /** 保存到收藏 */
  saveToFavorites: (recommendation: OutfitRecommendation, customName?: string) => Promise<string | null>;
  /** 从收藏中移除 */
  removeFromFavorites: (favoriteId: string) => Promise<boolean>;
  /** 检查是否已收藏 */
  isOutfitFavorited: (recommendationId: string) => Promise<boolean>;
  /** 刷新缓存 */
  refreshCache: () => void;
}

/**
 * 穿搭方案收藏管理 Hook
 */
export const useOutfitFavorites = (
  options: UseOutfitFavoritesOptions = {}
): UseOutfitFavoritesReturn => {
  const { autoLoad = true, cacheTime = 5 * 60 * 1000 } = options; // 默认缓存5分钟

  const [favorites, setFavorites] = useState<OutfitFavorite[]>([]);
  const [state, setState] = useState<FavoriteOperationState>({
    isSaving: false,
    isLoading: false,
    isDeleting: false,
    isSearching: false,
    isComparing: false,
  });

  // 缓存相关状态
  const cacheRef = useRef<{
    data: OutfitFavorite[];
    timestamp: number;
  } | null>(null);

  // 检查缓存是否有效
  const isCacheValid = useCallback(() => {
    if (!cacheRef.current) return false;
    return Date.now() - cacheRef.current.timestamp < cacheTime;
  }, [cacheTime]);

  // 更新缓存
  const updateCache = useCallback((data: OutfitFavorite[]) => {
    cacheRef.current = {
      data: [...data],
      timestamp: Date.now(),
    };
  }, []);

  // 清除缓存
  const clearCache = useCallback(() => {
    cacheRef.current = null;
  }, []);

  // 加载收藏列表
  const loadFavorites = useCallback(async () => {
    // 如果缓存有效，直接使用缓存
    if (isCacheValid() && cacheRef.current) {
      setFavorites(cacheRef.current.data);
      return;
    }

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

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

  // 保存到收藏
  const saveToFavorites = useCallback(async (
    recommendation: OutfitRecommendation,
    customName?: string
  ): Promise<string | null> => {
    setState(prev => ({ ...prev, isSaving: true, error: undefined }));

    try {
      const response = await OutfitFavoriteService.saveToFavorites(recommendation, customName);
      
      // 更新本地状态
      const newFavorites = [response.favorite, ...favorites];
      setFavorites(newFavorites);
      updateCache(newFavorites);

      return response.favorite_id;
    } catch (error) {
      console.error('保存收藏失败:', error);
      setState(prev => ({ 
        ...prev, 
        error: error instanceof Error ? error.message : '保存收藏失败' 
      }));
      return null;
    } finally {
      setState(prev => ({ ...prev, isSaving: false }));
    }
  }, [favorites, updateCache]);

  // 从收藏中移除
  const removeFromFavorites = useCallback(async (favoriteId: string): Promise<boolean> => {
    setState(prev => ({ ...prev, isDeleting: true, error: undefined }));

    try {
      const success = await OutfitFavoriteService.removeFromFavorites(favoriteId);
      
      if (success) {
        // 更新本地状态
        const newFavorites = favorites.filter(f => f.id !== favoriteId);
        setFavorites(newFavorites);
        updateCache(newFavorites);
      }

      return success;
    } catch (error) {
      console.error('删除收藏失败:', error);
      setState(prev => ({ 
        ...prev, 
        error: error instanceof Error ? error.message : '删除收藏失败' 
      }));
      return false;
    } finally {
      setState(prev => ({ ...prev, isDeleting: false }));
    }
  }, [favorites, updateCache]);

  // 检查是否已收藏
  const isOutfitFavorited = useCallback(async (recommendationId: string): Promise<boolean> => {
    try {
      // 首先检查本地缓存
      const localFavorite = favorites.find(f => f.recommendation_data.id === recommendationId);
      if (localFavorite) return true;

      // 如果本地没有，调用API检查
      return await OutfitFavoriteService.isOutfitFavorited(recommendationId);
    } catch (error) {
      console.error('检查收藏状态失败:', error);
      return false;
    }
  }, [favorites]);

  // 刷新缓存
  const refreshCache = useCallback(() => {
    clearCache();
    loadFavorites();
  }, [clearCache, loadFavorites]);

  // 自动加载
  useEffect(() => {
    if (autoLoad) {
      loadFavorites();
    }
  }, [autoLoad, loadFavorites]);

  return {
    favorites,
    state,
    loadFavorites,
    saveToFavorites,
    removeFromFavorites,
    isOutfitFavorited,
    refreshCache,
  };
};

export default useOutfitFavorites;
