import React, { useState, useCallback, useEffect } from 'react';
import { Heart, HeartIcon as HeartOutline, Loader2 } from 'lucide-react';
import { OutfitRecommendation } from '../../types/outfitRecommendation';
import { useOutfitFavorites } from '../../hooks/useOutfitFavorites';

interface FavoriteButtonProps {
  /** 穿搭方案 */
  recommendation: OutfitRecommendation;
  /** 是否已收藏 */
  isFavorited?: boolean;
  /** 收藏状态变化回调 */
  onFavoriteChange?: (isFavorited: boolean, favoriteId?: string) => void;
  /** 按钮大小 */
  size?: 'sm' | 'md' | 'lg';
  /** 是否显示文本 */
  showText?: boolean;
  /** 自定义类名 */
  className?: string;
}

/**
 * 收藏按钮组件
 * 遵循设计系统规范，提供统一的收藏操作界面
 */
export const FavoriteButton: React.FC<FavoriteButtonProps> = ({
  recommendation,
  isFavorited = false,
  onFavoriteChange,
  size = 'md',
  showText = false,
  className = '',
}) => {
  const [favorited, setFavorited] = useState(isFavorited);
  const [favoriteId, setFavoriteId] = useState<string>();

  const { saveToFavorites, removeFromFavorites, isOutfitFavorited, state } = useOutfitFavorites({
    autoLoad: false, // 不自动加载，按需检查
  });

  // 检查收藏状态
  useEffect(() => {
    const checkFavoriteStatus = async () => {
      try {
        const favorited = await isOutfitFavorited(recommendation.id);
        setFavorited(favorited);
      } catch (error) {
        console.error('检查收藏状态失败:', error);
      }
    };

    if (!isFavorited) {
      checkFavoriteStatus();
    }
  }, [recommendation.id, isFavorited, isOutfitFavorited]);

  // 处理收藏操作
  const handleFavoriteClick = useCallback(async (e: React.MouseEvent) => {
    e.stopPropagation(); // 防止触发父组件的点击事件

    if (state.isSaving || state.isDeleting) return;

    try {
      if (favorited) {
        // 取消收藏
        if (favoriteId) {
          const success = await removeFromFavorites(favoriteId);
          if (success) {
            setFavorited(false);
            setFavoriteId(undefined);
            onFavoriteChange?.(false);
          }
        }
      } else {
        // 添加收藏
        const newFavoriteId = await saveToFavorites(recommendation);
        if (newFavoriteId) {
          setFavorited(true);
          setFavoriteId(newFavoriteId);
          onFavoriteChange?.(true, newFavoriteId);
        }
      }
    } catch (error) {
      console.error('收藏操作失败:', error);
      // 这里可以添加错误提示
    }
  }, [favorited, favoriteId, recommendation, onFavoriteChange, state.isSaving, state.isDeleting, saveToFavorites, removeFromFavorites]);

  // 获取按钮尺寸样式
  const getSizeClasses = () => {
    switch (size) {
      case 'sm':
        return 'p-1.5 w-7 h-7';
      case 'lg':
        return 'p-3 w-12 h-12';
      default:
        return 'p-2 w-9 h-9';
    }
  };

  // 获取图标尺寸
  const getIconSize = () => {
    switch (size) {
      case 'sm':
        return 14;
      case 'lg':
        return 20;
      default:
        return 16;
    }
  };

  // 获取文本尺寸样式
  const getTextClasses = () => {
    switch (size) {
      case 'sm':
        return 'text-xs';
      case 'lg':
        return 'text-base';
      default:
        return 'text-sm';
    }
  };

  const iconSize = getIconSize();

  return (
    <button
      onClick={handleFavoriteClick}
      disabled={state.isSaving || state.isDeleting}
      className={`
        inline-flex items-center justify-center gap-2 rounded-full
        transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2
        ${favorited
          ? 'bg-red-500 text-white hover:bg-red-600 focus:ring-red-500 shadow-lg'
          : 'bg-white bg-opacity-80 text-gray-600 hover:bg-red-500 hover:text-white focus:ring-red-500 backdrop-blur-sm'
        }
        ${(state.isSaving || state.isDeleting) ? 'opacity-75 cursor-not-allowed' : 'hover:scale-105 active:scale-95'}
        ${getSizeClasses()}
        ${className}
      `}
      title={favorited ? '取消收藏' : '添加到收藏'}
    >
      {(state.isSaving || state.isDeleting) ? (
        <Loader2 size={iconSize} className="animate-spin" />
      ) : favorited ? (
        <Heart size={iconSize} className="fill-current" />
      ) : (
        <HeartOutline size={iconSize} />
      )}

      {showText && (
        <span className={`font-medium ${getTextClasses()}`}>
          {(state.isSaving || state.isDeleting) ? '处理中...' : favorited ? '已收藏' : '收藏'}
        </span>
      )}
    </button>
  );
};

export default FavoriteButton;
