'use client';

import { useState } from 'react';
import { useUserPreferences } from '@/contexts/UserPreferencesContext';
import { useDragAndDrop } from '@/hooks/useDragAndDrop';
import { Task, TaskStatus } from '@/lib/types';
import { TaskCard } from './TaskCard';
import { Card, CardHeader, CardContent } from '@/components/ui/Card';
import { Badge } from '@/components/ui/Badge';
import {
  DndContext,
  DragEndEvent,
  DragOverlay,
  DragStartEvent
} from '@dnd-kit/core';
import {
  SortableContext,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { useDroppable } from '@dnd-kit/core';

interface ObjectivesBoardProps {
  tasks: Task[];
  onEditTask?: (task: Task) => void;
  onUpdateStatus?: (taskId: string, newStatus: TaskStatus) => Promise<void>;
  compactView?: boolean;
  pinnedTagName?: string;
}

// Composant pour les colonnes droppables
function DroppableColumn({ 
  status, 
  tasks, 
  title,
  color,
  icon,
  onEditTask, 
  compactView 
}: {
  status: TaskStatus;
  tasks: Task[];
  title: string;
  color: string;
  icon: string;
  onEditTask?: (task: Task) => void;
  compactView: boolean;
}) {
  const { setNodeRef } = useDroppable({
    id: status,
  });

  return (
    <div ref={setNodeRef} className="space-y-3">
      <div className="flex items-center gap-2 pt-2 pb-2 border-b border-[var(--accent)]/20">
        <div className={`w-2 h-2 rounded-full ${color}`}></div>
        <h3 className={`text-sm font-mono font-medium uppercase tracking-wider ${color.replace('bg-', 'text-').replace('400', '300')}`}>
          {title}
        </h3>
        <div className="flex-1"></div>
        <span className="text-xs text-[var(--muted-foreground)] bg-[var(--card)] px-2 py-1 rounded">
          {tasks.length}
        </span>
      </div>
      
      {tasks.length === 0 ? (
        <div className="text-center py-8 text-[var(--muted-foreground)] text-sm">
          <div className="text-2xl mb-2">{icon}</div>
          Aucun objectif {title.toLowerCase()}
        </div>
      ) : (
        <SortableContext items={tasks.map(t => t.id)} strategy={verticalListSortingStrategy}>
          <div className="space-y-3">
            {tasks.map(task => (
              <div key={task.id} className="transform hover:scale-[1.02] transition-transform duration-200">
                <TaskCard
                  task={task}
                  onEdit={onEditTask}
                  compactView={compactView}
                />
              </div>
            ))}
          </div>
        </SortableContext>
      )}
    </div>
  );
}

export function ObjectivesBoard({ 
  tasks, 
  onEditTask, 
  onUpdateStatus,
  compactView = false,
  pinnedTagName = "Objectifs"
}: ObjectivesBoardProps) {
  const { preferences, toggleObjectivesCollapse } = useUserPreferences();
  const isCollapsed = preferences.viewPreferences.objectivesCollapsed;
  const { isMounted, sensors } = useDragAndDrop();
  const [activeTask, setActiveTask] = useState<Task | null>(null);

  // 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);
    }
  };
  
  if (tasks.length === 0) {
    return null; // Ne rien afficher s'il n'y a pas d'objectifs
  }

  const content = (
    <div className="bg-[var(--card)]/30 border-b border-[var(--accent)]/30">
      <div className="container mx-auto px-6 py-4">
          <Card variant="column" className="border-[var(--accent)]/30 shadow-[var(--accent)]/10">
            <CardHeader className="pb-4">
              <div className="flex items-center justify-between">
                <button
                  onClick={toggleObjectivesCollapse}
                  className="flex items-center gap-3 hover:bg-[var(--accent)]/20 rounded-lg p-2 -m-2 transition-colors group"
                >
                  <div className="w-3 h-3 bg-[var(--accent)] rounded-full animate-pulse shadow-[var(--accent)]/50 shadow-lg"></div>
                  <h2 className="text-lg font-mono font-bold text-[var(--accent)] uppercase tracking-wider">
                    🎯 Objectifs Principaux
                  </h2>
                  {pinnedTagName && (
                    <Badge variant="outline" className="border-[var(--accent)]/50 text-[var(--accent)]">
                      {pinnedTagName}
                    </Badge>
                  )}
                </button>
                
                <div className="flex items-center gap-2">
                  <Badge variant="primary" size="sm" className="bg-[var(--accent)]">
                    {String(tasks.length).padStart(2, '0')}
                  </Badge>
                  
                  {/* Bouton collapse séparé pour mobile */}
                  <button
                    onClick={toggleObjectivesCollapse}
                    className="lg:hidden p-1 hover:bg-[var(--accent)]/20 rounded transition-colors"
                    aria-label={isCollapsed ? "Développer" : "Réduire"}
                  >
                    <svg
                      className={`w-4 h-4 text-[var(--accent)] transition-transform duration-200 ${
                        isCollapsed ? '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>
              </div>
            </CardHeader>

            {!isCollapsed && (
              <CardContent className="pt-3">
                {(() => {
                // Séparer les tâches par statut
                const inProgressTasks = tasks.filter(task => task.status === 'in_progress');
                const todoTasks = tasks.filter(task => task.status === 'todo' || task.status === 'backlog');
                const completedTasks = tasks.filter(task => task.status === 'done' || task.status === 'archived');
                const frozenTasks = tasks.filter(task => task.status === 'freeze');

                return (
                  <div className="grid grid-cols-1 lg:grid-cols-4 gap-4">
                    <DroppableColumn
                      status="todo"
                      tasks={todoTasks}
                      title="À faire"
                      color="bg-[var(--primary)]"
                      icon="📋"
                      onEditTask={onEditTask}
                      compactView={compactView}
                    />
                    
                    <DroppableColumn
                      status="in_progress"
                      tasks={inProgressTasks}
                      title="En cours"
                      color="bg-yellow-400"
                      icon="🔄"
                      onEditTask={onEditTask}
                      compactView={compactView}
                    />
                    
                    <DroppableColumn
                      status="freeze"
                      tasks={frozenTasks}
                      title="Gelé"
                      color="bg-purple-400"
                      icon="🧊"
                      onEditTask={onEditTask}
                      compactView={compactView}
                    />
                    
                    <DroppableColumn
                      status="done"
                      tasks={completedTasks}
                      title="Terminé"
                      color="bg-green-400"
                      icon="✅"
                      onEditTask={onEditTask}
                      compactView={compactView}
                    />
                  </div>
                );
                })()}
              </CardContent>
            )}
          </Card>
        </div>
      </div>
  );

  if (!isMounted) {
    return content;
  }

  return (
    <DndContext
      id="objectives-board"
      sensors={sensors}
      onDragStart={handleDragStart}
      onDragEnd={handleDragEnd}
    >
      {content}
      
      {/* Overlay pour le drag & drop */}
      <DragOverlay>
        {activeTask ? (
          <div className="rotate-3 opacity-90">
            <TaskCard 
              task={activeTask} 
              onEdit={undefined}
              compactView={compactView}
            />
          </div>
        ) : null}
      </DragOverlay>
    </DndContext>
  );
}
