'use client';

import { useState } from 'react';
import { KanbanBoard } from './Board';
import { SwimlanesBoard } from './SwimlanesBoard';
import { ObjectivesBoard } from './ObjectivesBoard';
import { KanbanFilters } from './KanbanFilters';
import { EditTaskForm } from '@/components/forms/EditTaskForm';
import { useTasksContext } from '@/contexts/TasksContext';
import { Task, TaskStatus } from '@/lib/types';
import { UpdateTaskData } from '@/clients/tasks-client';

export function KanbanBoardContainer() {
  const { 
    filteredTasks, 
    pinnedTasks,
    loading, 
    createTask, 
    deleteTask, 
    updateTask, 
    updateTaskOptimistic,
    kanbanFilters,
    setKanbanFilters,
    tags
  } = useTasksContext();

  const [editingTask, setEditingTask] = useState<Task | null>(null);

  const handleEditTask = (task: Task) => {
    setEditingTask(task);
  };

  const handleUpdateTask = async (data: UpdateTaskData) => {
    await updateTask(data);
    setEditingTask(null);
  };

  const handleUpdateTitle = async (taskId: string, newTitle: string) => {
    await updateTask({
      taskId,
      title: newTitle
    });
  };

  const handleUpdateStatus = async (taskId: string, newStatus: TaskStatus) => {
    // Utiliser la mise à jour optimiste pour le drag & drop
    await updateTaskOptimistic({
      taskId,
      status: newStatus
    });
  };

  // Obtenir le nom du tag épinglé pour l'affichage
  const pinnedTagName = tags.find(tag => tag.isPinned)?.name;

  return (
    <>
      <KanbanFilters
        filters={kanbanFilters}
        onFiltersChange={setKanbanFilters}
      />
      
      {/* Section Objectifs Principaux */}
      {pinnedTasks.length > 0 && (
        <ObjectivesBoard
          tasks={pinnedTasks}
          onDeleteTask={deleteTask}
          onEditTask={handleEditTask}
          onUpdateTitle={handleUpdateTitle}
          compactView={kanbanFilters.compactView}
          pinnedTagName={pinnedTagName}
        />
      )}
      
      {kanbanFilters.swimlanesByTags ? (
        <SwimlanesBoard 
          tasks={filteredTasks}
          onDeleteTask={deleteTask}
          onEditTask={handleEditTask}
          onUpdateTitle={handleUpdateTitle}
          onUpdateStatus={handleUpdateStatus}
          compactView={kanbanFilters.compactView}
        />
      ) : (
        <KanbanBoard 
          tasks={filteredTasks}
          onCreateTask={createTask}
          onDeleteTask={deleteTask}
          onEditTask={handleEditTask}
          onUpdateTitle={handleUpdateTitle}
          onUpdateStatus={handleUpdateStatus}
          loading={loading}
          compactView={kanbanFilters.compactView}
        />
      )}
      
      <EditTaskForm
        isOpen={!!editingTask}
        onClose={() => setEditingTask(null)}
        onSubmit={handleUpdateTask}
        task={editingTask}
        loading={loading}
      />
    </>
  );
}
