'use client';

import { Task, TaskStatus } from '@/lib/types';
import { TaskCard } from './TaskCard';
import { useMemo, useState } from 'react';
import { useTasksContext } from '@/contexts/TasksContext';
import { useColumnVisibility } from '@/hooks/useColumnVisibility';
import { ColumnVisibilityToggle } from './ColumnVisibilityToggle';
import { getAllStatuses } from '@/lib/status-config';
import {
  DndContext,
  DragEndEvent,
  DragOverlay,
  DragStartEvent,
  closestCenter,
  PointerSensor,
  useSensor,
  useSensors,
} from '@dnd-kit/core';
import {
  SortableContext,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { useDroppable } from '@dnd-kit/core';
// import { SortableTaskCard } from './SortableTaskCard';

// Composant pour les colonnes droppables
function DroppableColumn({ 
  status, 
  tasks, 
  onDeleteTask, 
  onEditTask, 
  onUpdateTitle, 
  compactView 
}: {
  status: TaskStatus;
  tasks: Task[];
  onDeleteTask?: (taskId: string) => Promise<void>;
  onEditTask?: (task: Task) => void;
  onUpdateTitle?: (taskId: string, newTitle: string) => Promise<void>;
  compactView: boolean;
}) {
  const { setNodeRef, isOver } = useDroppable({
    id: status,
  });

  return (
    <div
      ref={setNodeRef}
      className={`min-h-[40px] p-2 rounded-lg transition-colors ${
        isOver ? 'bg-blue-900/20 border-2 border-blue-400/50' : 'bg-slate-800/20'
      }`}
    >
      <SortableContext items={tasks.map(t => t.id)} strategy={verticalListSortingStrategy}>
        <div className="space-y-1">
          {tasks.map(task => (
            <TaskCard
              key={task.id}
              task={task}
              onDelete={onDeleteTask}
              onEdit={onEditTask}
              onUpdateTitle={onUpdateTitle}
              compactView={compactView}
            />
          ))}
        </div>
      </SortableContext>
    </div>
  );
}

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 [activeTask, setActiveTask] = useState<Task | null>(null);
  const [collapsedSwimlanes, setCollapsedSwimlanes] = useState<Set<string>>(new Set());
  
  // Gestion de la visibilité des colonnes
  const { hiddenStatuses, toggleStatusVisibility, getVisibleStatuses } = useColumnVisibility();

  // Configuration des capteurs pour le drag & drop
  const sensors = useSensors(
    useSensor(PointerSensor, {
      activationConstraint: {
        distance: 8,
      },
    })
  );

  // Configuration des statuts basée sur la config centralisée
  const statuses = useMemo(() => {
    return getAllStatuses().map(statusConfig => ({
      id: statusConfig.key,
      title: statusConfig.label,
      color: statusConfig.color
    }));
  }, []);

  // Handlers pour le drag & drop
  const handleDragStart = (event: DragStartEvent) => {
    const task = tasks.find(t => t.id === event.active.id);
    setActiveTask(task || null);
  };

  const handleDragEnd = async (event: DragEndEvent) => {
    const { active, over } = event;
    setActiveTask(null);

    if (!over || !onUpdateStatus) return;

    const taskId = active.id as string;
    const newStatus = over.id as TaskStatus;
    
    // Vérifier si le statut a changé
    const task = tasks.find(t => t.id === taskId);
    if (task && task.status !== newStatus) {
      await onUpdateStatus(taskId, newStatus);
    }
  };

  const toggleSwimlane = (tagName: string) => {
    setCollapsedSwimlanes(prev => {
      const newSet = new Set(prev);
      if (newSet.has(tagName)) {
        newSet.delete(tagName);
      } else {
        newSet.add(tagName);
      }
      return newSet;
    });
  };

  // Filtrer les statuts visibles
  const visibleStatuses = getVisibleStatuses(statuses);

  // 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 (
    <DndContext
      sensors={sensors}
      collisionDetection={closestCenter}
      onDragStart={handleDragStart}
      onDragEnd={handleDragEnd}
      id="swimlanes-board"
    >
      <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 avec boutons toggle */}
      <div className="flex items-center justify-between px-6 pb-4">
        <ColumnVisibilityToggle
          hiddenStatuses={hiddenStatuses}
          onToggleStatus={toggleStatusVisibility}
        />
      </div>

      {/* Headers des colonnes visibles */}
      <div 
        className={`grid gap-4 px-6 pb-4 ml-8`}
        style={{ gridTemplateColumns: `repeat(${visibleStatuses.length}, 1fr)` }}
      >
        {visibleStatuses.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="flex items-center p-2 border-b border-slate-700/50">
                <button
                  onClick={() => toggleSwimlane(tagName)}
                  className="flex items-center gap-2 hover:bg-slate-800/50 rounded p-1 -m-1 transition-colors"
                >
                  <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>
                  <svg
                    className={`w-3 h-3 text-slate-400 transition-transform duration-200 ${
                      collapsedSwimlanes.has(tagName) ? 'rotate-180' : ''
                    }`}
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                  </svg>
                </button>
              </div>

              {/* Contenu de la swimlane */}
              {!collapsedSwimlanes.has(tagName) && (
                <div 
                  className="gap-4 p-2 ml-8 grid"
                  style={{ gridTemplateColumns: `repeat(${visibleStatuses.length}, 1fr)` }}
                >
                  {visibleStatuses.map(status => {
                    const statusTasks = tagTasks.filter(task => task.status === status.id);
                    return (
                      <DroppableColumn
                        key={status.id}
                        status={status.id}
                        tasks={statusTasks}
                        onDeleteTask={onDeleteTask}
                        onEditTask={onEditTask}
                        onUpdateTitle={onUpdateTitle}
                        compactView={compactView}
                      />
                    );
                  })}
                </div>
              )}
            </div>
          ))}
        </div>
      </div>
      </div>

      {/* DragOverlay pour l'aperçu pendant le drag */}
      <DragOverlay>
        {activeTask && (
          <TaskCard
            task={activeTask}
            compactView={compactView}
          />
        )}
      </DragOverlay>
    </DndContext>
  );
}
