'use client';

import { Task, TaskStatus } from '@/lib/types';
import { TaskCard } from './TaskCard';
import { QuickAddTask } from './QuickAddTask';
import { CreateTaskData } from '@/clients/tasks-client';
import { useState } from 'react';
import { useUserPreferences } from '@/contexts/UserPreferencesContext';
import { useDragAndDrop } from '@/hooks/useDragAndDrop';
import { getAllStatuses, getTechStyle } from '@/lib/status-config';
import { Card, CardHeader, ColumnHeader, DropZone } from '@/components/ui';
import {
  DndContext,
  DragEndEvent,
  DragOverlay,
  DragStartEvent,
  closestCenter
} from '@dnd-kit/core';
import {
  SortableContext,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { useDroppable } from '@dnd-kit/core';

// Composant pour les colonnes droppables
function DroppableColumn({ 
  status, 
  tasks, 
  onEditTask, 
  compactView,
  onCreateTask,
  showQuickAdd,
  onToggleQuickAdd,
  swimlaneContext
}: {
  status: TaskStatus;
  tasks: Task[];
  onEditTask?: (task: Task) => void;
  compactView: boolean;
  onCreateTask?: (data: CreateTaskData) => Promise<void>;
  showQuickAdd?: boolean;
  onToggleQuickAdd?: () => void;
  swimlaneContext?: {
    type: 'tag' | 'priority';
    value: string;
  };
}) {
  const { setNodeRef } = useDroppable({
    id: status,
  });

  return (
    <DropZone ref={setNodeRef} className="min-h-[100px] relative group/column">
      <SortableContext items={tasks.map(t => t.id)} strategy={verticalListSortingStrategy}>
        <div className="space-y-3">
          {tasks.map(task => (
            <TaskCard
              key={task.id}
              task={task}
              onEdit={onEditTask}
              compactView={compactView}
            />
          ))}
        </div>
      </SortableContext>
      
      {/* QuickAdd pour cette colonne - hors du flux, apparaît au hover */}
      {onCreateTask && (
        <>
          {showQuickAdd ? (
            <div className="mt-2">
              <QuickAddTask
                status={status}
                onSubmit={onCreateTask}
                onCancel={onToggleQuickAdd || (() => {})}
                swimlaneContext={swimlaneContext}
              />
            </div>
          ) : (
            <div className="h-0 flex justify-center opacity-0 group-hover/column:opacity-100 transition-opacity duration-200 pointer-events-none group-hover/column:pointer-events-auto">
              <button
                onClick={onToggleQuickAdd}
                className="py-1 px-2 transition-colors"
                title="Ajouter une tâche"
              >
                <div className="w-5 h-5 rounded-full bg-[var(--card)] hover:bg-[var(--card-hover)] flex items-center justify-center text-[var(--muted-foreground)] hover:text-[var(--foreground)] transition-all text-sm shadow-lg border border-[var(--border)]/30">
                  +
                </div>
              </button>
            </div>
          )}
        </>
      )}
    </DropZone>
  );
}

// Interface pour une swimlane
export interface SwimlaneData {
  key: string;
  label: string;
  icon?: string;
  color?: string;
  tasks: Task[];
  context?: {
    type: 'tag' | 'priority';
    value: string;
  };
}

interface SwimlanesBaseProps {
  tasks: Task[];
  swimlanes: SwimlaneData[];
  onCreateTask?: (data: CreateTaskData) => Promise<void>;
  onEditTask?: (task: Task) => void;
  onUpdateStatus?: (taskId: string, newStatus: TaskStatus) => Promise<void>;
  compactView?: boolean;
  visibleStatuses?: TaskStatus[];
}

export function SwimlanesBase({ 
  tasks, 
  swimlanes,
  onCreateTask,
  onEditTask, 
  onUpdateStatus, 
  compactView = false,
  visibleStatuses
}: SwimlanesBaseProps) {
  const [activeTask, setActiveTask] = useState<Task | null>(null);
  const [collapsedSwimlanes, setCollapsedSwimlanes] = useState<Set<string>>(new Set());
  const [showQuickAdd, setShowQuickAdd] = useState<{ [key: string]: boolean }>({});
  
  // Gestion de la visibilité des colonnes
  const { isColumnVisible } = useUserPreferences();
  const { isMounted, sensors } = useDragAndDrop();
  const allStatuses = getAllStatuses();
  const statusesToShow = visibleStatuses || 
    allStatuses.filter(status => isColumnVisible(status.key)).map(s => s.key);

  // 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);
    }
  };

  // Basculer l'état d'une swimlane
  const toggleSwimlane = (swimlaneKey: string) => {
    const newCollapsed = new Set(collapsedSwimlanes);
    if (newCollapsed.has(swimlaneKey)) {
      newCollapsed.delete(swimlaneKey);
    } else {
      newCollapsed.add(swimlaneKey);
    }
    setCollapsedSwimlanes(newCollapsed);
  };

  // Handlers pour la création de tâches

  const handleQuickAdd = async (data: CreateTaskData, columnId: string) => {
    if (onCreateTask) {
      await onCreateTask(data);
      setShowQuickAdd(prev => ({ ...prev, [columnId]: false }));
    }
  };

  const toggleQuickAdd = (columnId: string) => {
    setShowQuickAdd(prev => ({ ...prev, [columnId]: !prev[columnId] }));
  };

  const content = (
    <div className="flex flex-col h-full bg-[var(--background)]">
      {/* Espacement supérieur */}
      <div className="flex-shrink-0 py-2"></div>


        {/* Headers des colonnes visibles */}
        <div 
          className={`grid gap-4 px-6 py-4 ml-8`}
          style={{ gridTemplateColumns: `repeat(${statusesToShow.length}, minmax(0, 1fr))` }}
        >
          {statusesToShow.map(status => {
            const statusConfig = allStatuses.find(s => s.key === status);
            const techStyle = statusConfig ? getTechStyle(statusConfig.color) : null;
            const tasksInStatus = tasks.filter(task => task.status === status);
            
            return (
              <div key={status} className="text-center">
                <ColumnHeader
                  title={statusConfig?.label || status}
                  icon={statusConfig?.icon}
                  count={tasksInStatus.length}
                  color={techStyle?.accent.replace('text-', '')}
                  accentColor={techStyle?.accent}
                  className="justify-center gap-4"
                />
              </div>
            );
          })}
        </div>

        {/* Swimlanes */}
        <div className="flex-1 overflow-y-auto px-6">
          <div className="space-y-3 pb-2">
            {swimlanes.map(swimlane => {
              const isCollapsed = collapsedSwimlanes.has(swimlane.key);
              
              return (
                <Card key={swimlane.key} background="column" className="overflow-hidden">
                  {/* Header de la swimlane */}
                  <CardHeader padding="sm" separator={false}>
                    <button
                      onClick={() => toggleSwimlane(swimlane.key)}
                      className="flex items-center gap-2 hover:bg-[var(--card-hover)] rounded p-1 -m-1 transition-colors w-full"
                    >
                      <svg 
                        className={`w-4 h-4 text-[var(--muted-foreground)] transition-transform ${isCollapsed ? '' : 'rotate-90'}`}
                        fill="none" 
                        stroke="currentColor" 
                        viewBox="0 0 24 24"
                      >
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                      </svg>
                      {swimlane.color && (
                        <div
                          className="w-3 h-3 rounded-full"
                          style={{ backgroundColor: swimlane.color }}
                        />
                      )}
                      <span className="text-[var(--foreground)] font-medium text-sm">
                        {swimlane.icon && `${swimlane.icon} `}
                        {swimlane.label} ({swimlane.tasks.length})
                      </span>
                    </button>
                  </CardHeader>

                  {/* Contenu de la swimlane */}
                  {!isCollapsed && (
                    <div 
                      className={`grid gap-4 p-4`}
                      style={{ gridTemplateColumns: `repeat(${statusesToShow.length}, minmax(0, 1fr))` }}
                    >
                      {statusesToShow.map(status => {
                        const statusTasks = swimlane.tasks.filter(task => task.status === status);
                        
                        const columnId = `${swimlane.key}-${status}`;
                        
                        // Utiliser le contexte défini dans la swimlane
                        const swimlaneContext = swimlane.context;

                        return (
                          <DroppableColumn
                            key={columnId}
                            status={status}
                            tasks={statusTasks}
                            onEditTask={onEditTask}
                            compactView={compactView}
                            onCreateTask={onCreateTask ? (data) => handleQuickAdd(data, columnId) : undefined}
                            showQuickAdd={showQuickAdd[columnId] || false}
                            onToggleQuickAdd={() => toggleQuickAdd(columnId)}
                            swimlaneContext={swimlaneContext}
                          />
                        );
                      })}
                    </div>
                  )}
                </Card>
              );
            })}
          </div>
        </div>
      </div>
  );

  if (!isMounted) {
    return content;
  }

  return (
    <DndContext
      sensors={sensors}
      collisionDetection={closestCenter}
      onDragStart={handleDragStart}
      onDragEnd={handleDragEnd}
    >
      {content}
      
      {/* Drag overlay */}
      <DragOverlay>
        {activeTask && (
          <TaskCard
            task={activeTask}
            compactView={compactView}
          />
        )}
      </DragOverlay>
    </DndContext>
  );
}

