'use client';

import { Task, TaskStatus } from '@/lib/types';
import { TaskCard } from './TaskCard';
import { useMemo } from 'react';
import { useTasksContext } from '@/contexts/TasksContext';

interface SwimlanesboardProps {
  tasks: Task[];
  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;
}

export function SwimlanesBoard({ 
  tasks, 
  onDeleteTask, 
  onEditTask, 
  onUpdateTitle, 
  onUpdateStatus, 
  compactView = false 
}: SwimlanesboardProps) {
  const { tags: availableTags } = useTasksContext();

  const statuses: { id: TaskStatus; title: string; color: string }[] = [
    { id: 'todo', title: 'À faire', color: 'gray' },
    { id: 'in_progress', title: 'En cours', color: 'blue' },
    { id: 'done', title: 'Terminé', color: 'green' },
    { id: 'cancelled', title: 'Annulé', color: 'red' }
  ];

  // Grouper les tâches par tags
  const tasksByTag = useMemo(() => {
    const grouped: { [tagName: string]: Task[] } = {};
    
    // Ajouter une catégorie pour les tâches sans tags
    grouped['Sans tag'] = [];
    
    tasks.forEach(task => {
      if (!task.tags || task.tags.length === 0) {
        grouped['Sans tag'].push(task);
      } else {
        task.tags.forEach(tagName => {
          if (!grouped[tagName]) {
            grouped[tagName] = [];
          }
          grouped[tagName].push(task);
        });
      }
    });
    
    return grouped;
  }, [tasks]);

  // Obtenir la couleur d'un tag
  const getTagColor = (tagName: string) => {
    if (tagName === 'Sans tag') return '#64748b'; // slate-500
    const tag = availableTags.find(t => t.name === tagName);
    return tag?.color || '#64748b';
  };

  return (
    <div className="h-full flex flex-col bg-slate-950">
      {/* Header */}
      <div className="flex items-center gap-3 p-6 pb-4">
        <div className="w-2 h-2 bg-cyan-400 rounded-full animate-pulse"></div>
        <h2 className="text-lg font-mono font-bold text-slate-100 uppercase tracking-wider">
          Kanban Swimlanes
        </h2>
      </div>

      {/* Headers des colonnes */}
      <div className="grid grid-cols-5 gap-4 px-6 pb-4">
        <div className="text-sm font-mono font-bold text-slate-300 uppercase tracking-wider">
          Tags
        </div>
        {statuses.map(status => (
          <div key={status.id} className="text-center">
            <div className="text-sm font-mono font-bold text-slate-300 uppercase tracking-wider">
              {status.title}
            </div>
          </div>
        ))}
      </div>

      {/* Swimlanes */}
      <div className="flex-1 overflow-y-auto px-6">
        <div className="space-y-4">
          {Object.entries(tasksByTag)
            .sort(([a], [b]) => {
              // Mettre "Sans tag" à la fin
              if (a === 'Sans tag') return 1;
              if (b === 'Sans tag') return -1;
              return a.localeCompare(b);
            })
            .map(([tagName, tagTasks]) => (
            <div key={tagName} className="border border-slate-700/50 rounded-lg bg-slate-900/30">
              {/* Header de la swimlane */}
              <div className="grid grid-cols-5 gap-4 p-4 border-b border-slate-700/50">
                <div className="flex items-center gap-2">
                  <div 
                    className="w-3 h-3 rounded-full"
                    style={{ backgroundColor: getTagColor(tagName) }}
                  />
                  <span className="text-sm font-mono font-medium text-slate-200">
                    {tagName}
                  </span>
                  <span className="text-xs text-slate-400 bg-slate-700/50 px-2 py-1 rounded-full">
                    {tagTasks.length}
                  </span>
                </div>
                
                {/* Compteurs par statut */}
                {statuses.map(status => {
                  const count = tagTasks.filter(task => task.status === status.id).length;
                  return (
                    <div key={status.id} className="text-center">
                      <span className="text-xs text-slate-400 bg-slate-700/50 px-2 py-1 rounded-full">
                        {count}
                      </span>
                    </div>
                  );
                })}
              </div>

              {/* Contenu de la swimlane */}
              <div className="grid grid-cols-5 gap-4 p-4">
                <div></div> {/* Colonne vide pour le nom du tag */}
                
                {statuses.map(status => {
                  const statusTasks = tagTasks.filter(task => task.status === status.id);
                  return (
                    <div key={status.id} className="space-y-2 min-h-[100px]">
                      {statusTasks.map(task => (
                        <TaskCard
                          key={task.id}
                          task={task}
                          onDelete={onDeleteTask}
                          onEdit={onEditTask}
                          onUpdateTitle={onUpdateTitle}
                          compactView={compactView}
                        />
                      ))}
                    </div>
                  );
                })}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
