import { ITaskItem } from '@/contexts/types/tasks';

export const filterAndSortTasks = (
  tasks: ITaskItem[],
  filters: {
    type: string;
    status: string;
    priority: string;
    assignee: string;
  },
  sortConfig: {
    field: string;
    direction: 'asc' | 'desc';
  }
) => {
  // First, filter the tasks
  let filteredTasks = tasks.filter(task => {
    const typeMatch = filters.type === 'all' || task.type === filters.type;
    const statusMatch = filters.status === 'all' || task.status === filters.status;
    const priorityMatch = filters.priority === 'all' || task.priority === filters.priority;
    const assigneeMatch = filters.assignee === 'all' || 
      (task.collaboratorIds && task.collaboratorIds.includes(Number(filters.assignee)));

    return typeMatch && statusMatch && priorityMatch && assigneeMatch;
  });

  // Then, sort the filtered tasks
  const sortedTasks = [...filteredTasks].sort((a, b) => {
    let comparison = 0;

    switch (sortConfig.field) {
      case 'dueDate':
        comparison = new Date(a.endDate).getTime() - new Date(b.endDate).getTime();
        break;
      case 'createdAt':
        comparison = (new Date(a.lastModification || 0)).getTime() - (new Date(b.lastModification || 0)).getTime();
        break;
      case 'priority':
        const priorityOrder = { HIGH: 3, MEDIUM: 2, LOW: 1 } as const;
        comparison = (priorityOrder[a.priority as keyof typeof priorityOrder] || 0) - 
                     (priorityOrder[b.priority as keyof typeof priorityOrder] || 0);
        break;
      case 'status':
        const statusOrder = { 'TO DO': 1, 'IN PROGRESS': 2, 'DONE': 3 } as const;
        comparison = (statusOrder[a.status as keyof typeof statusOrder] || 0) - 
                     (statusOrder[b.status as keyof typeof statusOrder] || 0);
        break;
      default:
        comparison = 0;
    }

    return sortConfig.direction === 'asc' ? comparison : -comparison;
  });

  return sortedTasks;
}; 