'use client';

import { useState, useEffect } 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 { ChevronDown } from 'lucide-react';
import {
  DndContext,
  DragEndEvent,
  DragOverlay,
  DragStartEvent,
} from '@dnd-kit/core';
import {
  SortableContext,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { useDroppable } from '@dnd-kit/core';
import { Emoji } from '@/components/ui/Emoji';
import { getAllStatuses, getTechStyle } from '@/lib/status-config';
import { DropZone, ColumnHeader } from '@/components/ui';

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

// Composant pour les colonnes droppables
function DroppableColumn({
  status,
  tasks,
  onEditTask,
  compactView,
}: {
  status: TaskStatus;
  tasks: Task[];
  onEditTask?: (task: Task) => void;
  compactView: boolean;
}) {
  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>
    </DropZone>
  );
}

export function ObjectivesBoard({
  tasks,
  onEditTask,
  onUpdateStatus,
  compactView = false,
  pinnedTagName = 'Objectifs',
  visibleStatuses,
}: ObjectivesBoardProps) {
  const { preferences, toggleObjectivesCollapse, isColumnVisible } =
    useUserPreferences();
  const { isMounted, sensors } = useDragAndDrop();
  const [activeTask, setActiveTask] = useState<Task | null>(null);
  const [isCollapsed, setIsCollapsed] = useState(true); // Initialiser à true pour éviter l'hydratation mismatch

  // Synchroniser avec les préférences après le montage
  useEffect(() => {
    setIsCollapsed(preferences.viewPreferences.objectivesCollapsed);
  }, [preferences.viewPreferences.objectivesCollapsed]);

  // Handler pour toggle qui met à jour les préférences ET l'état local
  const handleToggleCollapse = () => {
    toggleObjectivesCollapse();
    setIsCollapsed(!isCollapsed);
  };

  // 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">
      <Card
        variant="column"
        className="border-[var(--accent)]/30 shadow-[var(--accent)]/10"
      >
        <CardHeader className="pb-4 px-6">
          <div className="flex items-center justify-between">
            <button
              onClick={handleToggleCollapse}
              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">
                <Emoji emoji="🎯" /> 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={handleToggleCollapse}
                className="lg:hidden p-1 hover:bg-[var(--accent)]/20 rounded transition-colors"
                aria-label={isCollapsed ? 'Développer' : 'Réduire'}
              >
                <ChevronDown
                  className={`w-4 h-4 text-[var(--accent)] transition-transform duration-200 ${
                    isCollapsed ? 'rotate-180' : ''
                  }`}
                />
              </button>
            </div>
          </div>
        </CardHeader>

        {!isCollapsed && (
          <CardContent className="pt-3 px-0">
            {(() => {
              // Obtenir toutes les colonnes configurées
              const allColumns = getAllStatuses();

              // Filtrer les colonnes visibles selon le filtrage global
              const visibleColumns = visibleStatuses
                ? allColumns.filter((col) => visibleStatuses.includes(col.key))
                : allColumns.filter((col) => isColumnVisible(col.key));

              // Organiser les tâches par statut (comme dans le Kanban principal)
              const tasksByStatus = tasks.reduce(
                (acc, task) => {
                  if (!acc[task.status]) {
                    acc[task.status] = [];
                  }
                  acc[task.status].push(task);
                  return acc;
                },
                {} as Record<TaskStatus, Task[]>
              );

              // Mapper les colonnes visibles avec leurs tâches
              const columnsWithTasks = visibleColumns.map((colConfig) => {
                return {
                  config: colConfig,
                  tasks: tasksByStatus[colConfig.key] || [],
                };
              });

              if (columnsWithTasks.length === 0) {
                return (
                  <div className="text-center py-8 text-[var(--muted-foreground)] text-sm">
                    Aucune colonne visible
                  </div>
                );
              }

              return (
                <>
                  {/* Headers des colonnes */}
                  <div
                    className={`grid gap-4 px-6 py-4`}
                    style={{
                      gridTemplateColumns: `repeat(${columnsWithTasks.length}, minmax(0, 1fr))`,
                    }}
                  >
                    {columnsWithTasks.map(({ config }) => {
                      const style = getTechStyle(config.color);
                      const tasksInStatus = tasksByStatus[config.key] || [];
                      return (
                        <div key={config.key} className="text-center">
                          <ColumnHeader
                            title={config.label}
                            icon={config.icon}
                            count={tasksInStatus.length}
                            color={style.accent.replace('text-', '')}
                            accentColor={style.accent}
                            className="justify-center gap-4"
                          />
                        </div>
                      );
                    })}
                  </div>

                  {/* Colonnes avec les tâches */}
                  <div
                    className={`grid gap-4 px-6 pb-4`}
                    style={{
                      gridTemplateColumns: `repeat(${columnsWithTasks.length}, minmax(0, 1fr))`,
                    }}
                  >
                    {columnsWithTasks.map(({ config, tasks: columnTasks }) => {
                      return (
                        <DroppableColumn
                          key={config.key}
                          status={config.key}
                          tasks={columnTasks}
                          onEditTask={onEditTask}
                          compactView={compactView}
                        />
                      );
                    })}
                  </div>
                </>
              );
            })()}
          </CardContent>
        )}
      </Card>
    </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>
  );
}
