import { useMemo } from 'react';
import { motion } from 'framer-motion';

/**
 * PC용 카테고리 필터 컴포넌트
 * @param {Array} categories - 카테고리 목록
 * @param {Array} selectedCategories - 선택된 카테고리 ID 목록
 * @param {function} onToggle - 카테고리 토글 핸들러
 * @param {function} onClear - 전체 선택 핸들러
 * @param {Map} categoryCounts - 카테고리별 개수 맵
 * @param {boolean} disabled - 비활성화 여부
 */
function CategoryFilter({
  categories,
  selectedCategories,
  onToggle,
  onClear,
  categoryCounts,
  disabled = false,
}) {
  // 정렬된 카테고리 목록 (개수 기준, '기타'는 맨 뒤)
  const sortedCategories = useMemo(() => {
    return categories
      .map((category) => ({
        ...category,
        count: categoryCounts.get(category.id) || 0,
      }))
      .filter((category) => category.count > 0)
      .sort((a, b) => {
        if (a.name === '기타') return 1;
        if (b.name === '기타') return -1;
        return b.count - a.count;
      });
  }, [categories, categoryCounts]);

  const totalCount = categoryCounts.get('total') || 0;

  return (
    <motion.div
      animate={{ opacity: disabled ? 0.4 : 1 }}
      transition={{ duration: 0.2 }}
      className={`bg-white rounded-2xl shadow-sm p-6 flex flex-col min-h-0 ${disabled ? 'pointer-events-none' : ''}`}
    >
      <h3 className="font-bold text-gray-900 mb-4 flex-shrink-0">카테고리</h3>
      <div className="space-y-1 flex-1 min-h-0 overflow-y-auto -mr-3 pr-3">
        {/* 전체 */}
        <button
          onClick={onClear}
          className={`w-full flex items-center justify-between px-3 py-3 rounded-lg transition-colors ${
            selectedCategories.length === 0 ? 'bg-primary/10 text-primary' : 'hover:bg-gray-50'
          }`}
        >
          <div className="flex items-center gap-2">
            <span className="w-3 h-3 rounded-full bg-gray-400" />
            <span>전체</span>
          </div>
          <span className="text-sm text-gray-400">{totalCount}</span>
        </button>

        {/* 개별 카테고리 */}
        {sortedCategories.map((category) => {
          const isSelected = selectedCategories.includes(category.id);
          return (
            <button
              key={category.id}
              onClick={() => onToggle(category.id)}
              className={`w-full flex items-center justify-between px-3 py-3 rounded-lg transition-colors ${
                isSelected ? 'bg-primary/10 text-primary' : 'hover:bg-gray-50'
              }`}
            >
              <div className="flex items-center gap-2">
                <span className="w-3 h-3 rounded-full" style={{ backgroundColor: category.color }} />
                <span>{category.name}</span>
              </div>
              <span className="text-sm text-gray-400">{category.count}</span>
            </button>
          );
        })}
      </div>
    </motion.div>
  );
}

export default CategoryFilter;
