import React, { useState, useEffect, useCallback } from 'react';
import { Search, Grid, List, Trash2, Eye, Loader2, Heart } from 'lucide-react';
import { OutfitFavorite, FavoriteViewMode, FAVORITE_SORT_OPTIONS } from '../../types/outfitFavorite';
import { OutfitFavoriteService } from '../../services/outfitFavoriteService';

interface FavoriteOutfitListProps {
  /** 收藏方案选择回调 */
  onFavoriteSelect?: (favorite: OutfitFavorite) => void;
  /** 收藏方案删除回调 */
  onFavoriteDelete?: (favoriteId: string) => void;
  /** 查看详情回调 */
  onViewDetails?: (favorite: OutfitFavorite) => void;
  /** 自定义类名 */
  className?: string;
}

/**
 * 收藏穿搭方案列表组件
 * 遵循设计系统规范，提供统一的收藏列表展示界面
 */
export const FavoriteOutfitList: React.FC<FavoriteOutfitListProps> = ({
  onFavoriteSelect,
  onFavoriteDelete,
  onViewDetails,
  className = '',
}) => {
  const [favorites, setFavorites] = useState<OutfitFavorite[]>([]);
  const [filteredFavorites, setFilteredFavorites] = useState<OutfitFavorite[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [sortBy, setSortBy] = useState('created_at_desc');
  const [viewMode, setViewMode] = useState<FavoriteViewMode>(FavoriteViewMode.Grid);

  // 加载收藏列表
  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]);

  // 过滤和排序
  useEffect(() => {
    let filtered = OutfitFavoriteService.filterFavorites(favorites, searchTerm);
    filtered = OutfitFavoriteService.sortFavorites(filtered, sortBy);
    setFilteredFavorites(filtered);
  }, [favorites, searchTerm, sortBy]);

  // 处理删除收藏
  const handleDelete = useCallback(async (favoriteId: string) => {
    if (!confirm('确定要删除这个收藏吗？')) return;

    try {
      await OutfitFavoriteService.removeFromFavorites(favoriteId);
      setFavorites(prev => prev.filter(f => f.id !== favoriteId));
      onFavoriteDelete?.(favoriteId);
    } catch (err) {
      console.error('删除收藏失败:', err);
      setError(err instanceof Error ? err.message : '删除收藏失败');
    }
  }, [onFavoriteDelete]);

  // 渲染收藏卡片
  const renderFavoriteCard = (favorite: OutfitFavorite) => {
    const displayName = OutfitFavoriteService.getDisplayName(favorite);
    const description = OutfitFavoriteService.getDescription(favorite);
    const styleTags = OutfitFavoriteService.getStyleTags(favorite);
    const occasions = OutfitFavoriteService.getOccasions(favorite);
    const createdAt = OutfitFavoriteService.formatCreatedAt(favorite);

    return (
      <div
        key={favorite.id}
        className={`
          bg-white rounded-xl border border-gray-200 shadow-sm hover:shadow-md
          transition-all duration-200 cursor-pointer group
          ${viewMode === FavoriteViewMode.List ? 'flex items-center p-4' : 'p-4'}
        `}
        onClick={() => onFavoriteSelect?.(favorite)}
      >
        {/* 收藏图标 */}
        <div className={`
          flex-shrink-0 w-12 h-12 bg-gradient-to-br from-red-500 to-pink-600
          rounded-xl flex items-center justify-center shadow-lg
          ${viewMode === FavoriteViewMode.List ? 'mr-4' : 'mb-3'}
        `}>
          <Heart className="w-6 h-6 text-white fill-current" />
        </div>

        {/* 内容区域 */}
        <div className="flex-1 min-w-0">
          <div className="flex items-start justify-between mb-2">
            <h3 className="text-lg font-semibold text-gray-900 truncate">
              {displayName}
            </h3>
            <div className="flex items-center gap-1 ml-2">
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  onViewDetails?.(favorite);
                }}
                className="p-1.5 text-gray-400 hover:text-blue-600 rounded-lg hover:bg-blue-50 transition-colors"
                title="查看详情"
              >
                <Eye className="w-4 h-4" />
              </button>
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  handleDelete(favorite.id);
                }}
                className="p-1.5 text-gray-400 hover:text-red-600 rounded-lg hover:bg-red-50 transition-colors"
                title="删除收藏"
              >
                <Trash2 className="w-4 h-4" />
              </button>
            </div>
          </div>

          <p className="text-gray-600 text-sm mb-3 line-clamp-2">
            {description}
          </p>

          {/* 标签 */}
          <div className="flex flex-wrap gap-1 mb-3">
            {styleTags.slice(0, 3).map((tag, index) => (
              <span
                key={index}
                className="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full"
              >
                {tag}
              </span>
            ))}
            {occasions.slice(0, 2).map((occasion, index) => (
              <span
                key={index}
                className="px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full"
              >
                {occasion}
              </span>
            ))}
          </div>

          {/* 收藏时间 */}
          <div className="text-xs text-gray-500">
            收藏于 {createdAt}
          </div>
        </div>
      </div>
    );
  };

  if (isLoading) {
    return (
      <div className={`space-y-6 ${className}`}>
        <div className="flex items-center justify-center py-12">
          <Loader2 className="w-8 h-8 text-primary-500 animate-spin" />
          <span className="ml-3 text-gray-600">加载收藏列表...</span>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className={`space-y-6 ${className}`}>
        <div className="text-center py-12">
          <p className="text-red-600 mb-4">{error}</p>
          <button
            onClick={loadFavorites}
            className="px-4 py-2 bg-primary-500 text-white rounded-lg hover:bg-primary-600 transition-colors"
          >
            重新加载
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className={`space-y-6 ${className}`}>
      {/* 工具栏 */}
      <div className="flex items-center justify-between gap-4">
        {/* 搜索框 */}
        <div className="flex-1 max-w-md 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-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
          />
        </div>

        {/* 排序和视图切换 */}
        <div className="flex items-center gap-3">
          <select
            value={sortBy}
            onChange={(e) => setSortBy(e.target.value)}
            className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
          >
            {FAVORITE_SORT_OPTIONS.map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>

          <div className="flex items-center border border-gray-300 rounded-lg">
            <button
              onClick={() => setViewMode(FavoriteViewMode.Grid)}
              className={`p-2 ${viewMode === FavoriteViewMode.Grid ? 'bg-primary-500 text-white' : 'text-gray-600 hover:bg-gray-100'}`}
            >
              <Grid className="w-4 h-4" />
            </button>
            <button
              onClick={() => setViewMode(FavoriteViewMode.List)}
              className={`p-2 ${viewMode === FavoriteViewMode.List ? 'bg-primary-500 text-white' : 'text-gray-600 hover:bg-gray-100'}`}
            >
              <List className="w-4 h-4" />
            </button>
          </div>
        </div>
      </div>

      {/* 收藏列表 */}
      {filteredFavorites.length === 0 ? (
        <div className="text-center py-12">
          <Heart className="w-16 h-16 text-gray-300 mx-auto mb-4" />
          <h3 className="text-lg font-semibold text-gray-900 mb-2">
            {searchTerm ? '没有找到匹配的收藏' : '暂无收藏方案'}
          </h3>
          <p className="text-gray-500">
            {searchTerm ? '尝试调整搜索条件' : '开始收藏您喜欢的穿搭方案吧'}
          </p>
        </div>
      ) : (
        <div className={
          viewMode === FavoriteViewMode.Grid
            ? 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6'
            : 'space-y-4'
        }>
          {filteredFavorites.map(renderFavoriteCard)}
        </div>
      )}
    </div>
  );
};

export default FavoriteOutfitList;
