import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Heart, ChevronDown, Search, Loader2 } from 'lucide-react';
import { OutfitFavorite } from '../../types/outfitFavorite';
import { OutfitFavoriteService } from '../../services/outfitFavoriteService';

interface FavoriteSelectorProps {
  /** 当前选中的收藏方案 */
  selectedFavorite?: OutfitFavorite | null;
  /** 选择变化回调 */
  onSelectionChange?: (favorite: OutfitFavorite | null) => void;
  /** 占位符文本 */
  placeholder?: string;
  /** 是否禁用 */
  disabled?: boolean;
  /** 自定义类名 */
  className?: string;
}

/**
 * 收藏方案选择器组件
 * 提供下拉选择收藏的穿搭方案功能
 */
export const FavoriteSelector: React.FC<FavoriteSelectorProps> = ({
  selectedFavorite,
  onSelectionChange,
  placeholder = '选择收藏方案...',
  disabled = false,
  className = '',
}) => {
  const [favorites, setFavorites] = useState<OutfitFavorite[]>([]);
  const [isOpen, setIsOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const containerRef = useRef<HTMLDivElement>(null);

  // 加载收藏列表
  const loadFavorites = useCallback(async () => {
    setIsLoading(true);
    setError(null);

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

  // 初始加载
  useEffect(() => {
    loadFavorites();
  }, [loadFavorites]);

  // 过滤收藏列表
  const filteredFavorites = React.useMemo(() => {
    return OutfitFavoriteService.filterFavorites(favorites, searchTerm);
  }, [favorites, searchTerm]);

  // 处理选择
  const handleSelect = useCallback((favorite: OutfitFavorite | null) => {
    onSelectionChange?.(favorite);
    setIsOpen(false);
    setSearchTerm('');
  }, [onSelectionChange]);

  // 处理点击外部关闭
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as HTMLElement;
      if (!target.closest('.favorite-selector')) {
        setIsOpen(false);
        setSearchTerm('');
      }
    };

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
      return () => document.removeEventListener('mousedown', handleClickOutside);
    }
  }, [isOpen]);

  return (
    <div ref={containerRef} className={`relative favorite-selector ${className}`} style={{ position: 'relative', zIndex: 100 }}>
      {/* 选择器按钮 */}
      <button
        onClick={() => !disabled && setIsOpen(!isOpen)}
        disabled={disabled}
        className={`
          w-full flex items-center justify-between px-4 py-3 bg-white border border-gray-300 rounded-lg
          transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500
          ${disabled ? 'opacity-50 cursor-not-allowed' : 'hover:border-gray-400 cursor-pointer'}
          ${isOpen ? 'border-primary-500 ring-2 ring-primary-500' : ''}
        `}
      >
        <div className="flex items-center gap-3 flex-1 min-w-0">
          {selectedFavorite ? (
            <>
              <div className="w-6 h-6 bg-gradient-to-br from-red-500 to-pink-600 rounded-md flex items-center justify-center shadow-sm flex-shrink-0">
                <Heart className="w-3 h-3 text-white fill-current" />
              </div>
              <div className="flex-1 min-w-0 text-left">
                <p className="text-sm font-medium text-gray-900 truncate">
                  {OutfitFavoriteService.getDisplayName(selectedFavorite)}
                </p>
                <p className="text-xs text-gray-500 truncate">
                  {OutfitFavoriteService.getStyleTags(selectedFavorite).slice(0, 2).join(', ')}
                </p>
              </div>
            </>
          ) : (
            <>
              <Heart className="w-5 h-5 text-gray-400" />
              <span className="text-gray-500">{placeholder}</span>
            </>
          )}
        </div>
        <ChevronDown className={`w-5 h-5 text-gray-400 transition-transform duration-200 ${isOpen ? 'rotate-180' : ''}`} />
      </button>

      {/* 下拉菜单 */}
      {isOpen && (
        <div className="absolute top-full left-0 right-0 mt-1 bg-white border border-gray-300 rounded-lg shadow-xl z-[9999] max-h-80 overflow-hidden" style={{ boxShadow: '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)' }}>
          {/* 搜索框 */}
          <div className="p-3 border-b border-gray-200">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
              <input
                type="text"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                placeholder="搜索收藏方案..."
                className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-primary-500 focus:border-primary-500 text-sm"
                autoFocus
              />
            </div>
          </div>

          {/* 选项列表 */}
          <div className="max-h-60 overflow-y-auto">
            {isLoading ? (
              <div className="flex items-center justify-center py-6">
                <Loader2 className="w-5 h-5 text-primary-500 animate-spin" />
                <span className="ml-2 text-sm text-gray-600">加载中...</span>
              </div>
            ) : error ? (
              <div className="p-4 text-center">
                <p className="text-red-600 text-sm mb-2">{error}</p>
                <button
                  onClick={loadFavorites}
                  className="text-primary-600 text-sm hover:text-primary-700"
                >
                  重新加载
                </button>
              </div>
            ) : filteredFavorites.length === 0 ? (
              <div className="p-4 text-center">
                <Heart className="w-8 h-8 text-gray-300 mx-auto mb-2" />
                <p className="text-gray-500 text-sm">
                  {searchTerm ? '没有找到匹配的收藏' : '暂无收藏方案'}
                </p>
              </div>
            ) : (
              <>
                {/* 清除选择选项 */}
                {selectedFavorite && (
                  <button
                    onClick={() => handleSelect(null)}
                    className="w-full px-4 py-3 text-left hover:bg-gray-50 border-b border-gray-100 text-sm text-gray-600"
                  >
                    清除选择
                  </button>
                )}

                {/* 收藏方案列表 */}
                {filteredFavorites.map((favorite) => (
                  <button
                    key={favorite.id}
                    onClick={() => handleSelect(favorite)}
                    className={`
                      w-full px-4 py-3 text-left hover:bg-gray-50 transition-colors
                      ${selectedFavorite?.id === favorite.id ? 'bg-primary-50 border-l-4 border-primary-500' : ''}
                    `}
                  >
                    <div className="flex items-start gap-3">
                      <div className="w-6 h-6 bg-gradient-to-br from-red-500 to-pink-600 rounded-md flex items-center justify-center shadow-sm flex-shrink-0 mt-0.5">
                        <Heart className="w-3 h-3 text-white fill-current" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium text-gray-900 mb-1 truncate">
                          {OutfitFavoriteService.getDisplayName(favorite)}
                        </p>
                        <p className="text-xs text-gray-600 line-clamp-2 mb-1">
                          {OutfitFavoriteService.getDescription(favorite)}
                        </p>
                        <div className="flex flex-wrap gap-1">
                          {OutfitFavoriteService.getStyleTags(favorite).slice(0, 2).map((tag, index) => (
                            <span
                              key={index}
                              className="px-1.5 py-0.5 bg-blue-100 text-blue-700 text-xs rounded"
                            >
                              {tag}
                            </span>
                          ))}
                        </div>
                        <p className="text-xs text-gray-400 mt-1">
                          {OutfitFavoriteService.formatCreatedAt(favorite)}
                        </p>
                      </div>
                    </div>
                  </button>
                ))}
              </>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default FavoriteSelector;
