'use client';

import { useMemo } from 'react';
import { TaskPriority } from '@/lib/types';
import { useTasksContext } from '@/contexts/TasksContext';
import { getAllPriorities, getPriorityColorHex } from '@/lib/status-config';
import { FilterChip } from '@/components/ui';

interface PriorityFiltersProps {
  selectedPriorities?: TaskPriority[];
  onPriorityToggle: (priority: TaskPriority) => void;
}

export function PriorityFilters({
  selectedPriorities = [],
  onPriorityToggle,
}: PriorityFiltersProps) {
  const { regularTasks } = useTasksContext();

  // Calculer les compteurs pour les priorités basés sur toutes les tâches
  const priorityCounts = useMemo(() => {
    const counts: Record<string, number> = {};
    getAllPriorities().forEach((priority) => {
      counts[priority.key] = regularTasks.filter(
        (task) => task.priority === priority.key
      ).length;
    });
    return counts;
  }, [regularTasks]);

  const priorityOptions = getAllPriorities().map((priorityConfig) => ({
    value: priorityConfig.key,
    label: priorityConfig.label,
    color: priorityConfig.color,
    count: priorityCounts[priorityConfig.key] || 0,
  }));

  // Filtrer les priorités qui ont des tâches visibles
  const visiblePriorities = priorityOptions.filter(
    (priority) => priority.count > 0
  );

  return (
    <div className="space-y-2">
      <label className="block text-xs font-mono font-medium text-[var(--muted-foreground)] uppercase tracking-wider">
        Priorités
      </label>
      {visiblePriorities.length === 0 ? (
        <div className="text-xs text-[var(--muted-foreground)] italic">
          Aucune priorité disponible dans les tâches filtrées
        </div>
      ) : (
        <div className="flex flex-wrap gap-1">
          {visiblePriorities.map((priority) => (
            <FilterChip
              key={priority.value}
              onClick={() => onPriorityToggle(priority.value)}
              variant={
                selectedPriorities.includes(priority.value)
                  ? 'selected'
                  : 'priority'
              }
              color={getPriorityColorHex(priority.color)}
              count={priority.count}
            >
              {priority.label}
            </FilterChip>
          ))}
        </div>
      )}
    </div>
  );
}
