'use client';

import { Task, TaskStatus } from '@/lib/types';
import { CreateTaskData } from '@/clients/tasks-client';
import { useMemo } from 'react';
import { getAllPriorities } from '@/lib/status-config';
import { SwimlanesBase, SwimlaneData } from './SwimlanesBase';

interface PrioritySwimlanesBoardProps {
  loading: boolean;
  tasks: Task[];
  onCreateTask?: (data: CreateTaskData) => Promise<void>;
  onDeleteTask?: (taskId: string) => Promise<void>;
  onEditTask?: (task: Task) => void;
  onUpdateTitle?: (taskId: string, newTitle: string) => Promise<void>;
  onUpdateStatus?: (taskId: string, newStatus: TaskStatus) => Promise<void>;
  compactView?: boolean;
  visibleStatuses?: TaskStatus[];
}

export function PrioritySwimlanesBoard({
  tasks,
  onCreateTask,
  onDeleteTask,
  onEditTask,
  onUpdateTitle,
  onUpdateStatus,
  compactView = false,
  visibleStatuses,
}: PrioritySwimlanesBoardProps) {
  // Grouper les tâches par priorités et créer les données de swimlanes
  const swimlanesData = useMemo((): SwimlaneData[] => {
    const grouped: { [priorityKey: string]: Task[] } = {};

    // Initialiser avec toutes les priorités
    getAllPriorities().forEach((priority) => {
      grouped[priority.key] = [];
    });

    tasks.forEach((task) => {
      if (grouped[task.priority]) {
        grouped[task.priority].push(task);
      }
    });

    // Convertir en format SwimlaneData en respectant l'ordre de priorité
    // Filtrer uniquement les priorités qui ont des tâches
    return getAllPriorities()
      .sort((a, b) => b.order - a.order) // Ordre décroissant - plus importantes en haut
      .filter((priority) => grouped[priority.key].length > 0) // Ne garder que les priorités avec des tâches
      .map((priority) => ({
        key: priority.key,
        label: priority.label,
        icon: priority.icon,
        color: priority.color,
        tasks: grouped[priority.key],
        context: {
          type: 'priority' as const,
          value: priority.key,
        },
      }));
  }, [tasks]);

  return (
    <SwimlanesBase
      tasks={tasks}
      swimlanes={swimlanesData}
      onCreateTask={onCreateTask}
      onDeleteTask={onDeleteTask}
      onEditTask={onEditTask}
      onUpdateTitle={onUpdateTitle}
      onUpdateStatus={onUpdateStatus}
      compactView={compactView}
      visibleStatuses={visibleStatuses}
    />
  );
}
