'use client';

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

interface KanbanBoardContainerProps {
  showFilters?: boolean;
  showObjectives?: boolean;
}

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

  const { preferences, toggleColumnVisibility, isColumnVisible } = useUserPreferences();
  
  const allStatuses = getAllStatuses();
  const visibleStatuses = allStatuses.filter(status => isColumnVisible(status.key)).map(s => s.key);
  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;

  // Wrapper pour adapter le type de createTask
  const handleCreateTask = async (data: CreateTaskData): Promise<void> => {
    await createTask(data);
  };

  return (
    <>
      {/* Barre de filtres - conditionnelle */}
      {showFilters && (
        <KanbanFilters 
          filters={kanbanFilters} 
          onFiltersChange={setKanbanFilters}
          hiddenStatuses={new Set(preferences.columnVisibility.hiddenStatuses)}
          onToggleStatusVisibility={toggleColumnVisibility}
        />
      )}
      
      {/* Section Objectifs Principaux - conditionnelle */}
      {showObjectives && pinnedTasks.length > 0 && (
        <ObjectivesBoard
          tasks={pinnedTasks}
          onDeleteTask={deleteTask}
          onEditTask={handleEditTask}
          onUpdateTitle={handleUpdateTitle}
          onUpdateStatus={handleUpdateStatus}
          compactView={kanbanFilters.compactView}
          pinnedTagName={pinnedTagName}
        />
      )}
      
      {kanbanFilters.swimlanesByTags ? (
        kanbanFilters.swimlanesMode === 'priority' ? (
          <PrioritySwimlanesBoard 
            tasks={filteredTasks}
            onCreateTask={handleCreateTask}
            onDeleteTask={deleteTask}
            onEditTask={handleEditTask}
            onUpdateTitle={handleUpdateTitle}
            onUpdateStatus={handleUpdateStatus}
            compactView={kanbanFilters.compactView}
            visibleStatuses={visibleStatuses}
            loading={loading}
          />
        ) : (
          <SwimlanesBoard 
            tasks={filteredTasks}
            onCreateTask={handleCreateTask}
            onDeleteTask={deleteTask}
            onEditTask={handleEditTask}
            onUpdateTitle={handleUpdateTitle}
            onUpdateStatus={handleUpdateStatus}
            compactView={kanbanFilters.compactView}
            visibleStatuses={visibleStatuses}
            loading={loading}
          />
        )
      ) : (
        <KanbanBoard 
          tasks={filteredTasks}
          onCreateTask={handleCreateTask}
          onDeleteTask={deleteTask}
          onEditTask={handleEditTask}
          onUpdateTitle={handleUpdateTitle}
          onUpdateStatus={handleUpdateStatus}
          compactView={kanbanFilters.compactView}
          visibleStatuses={visibleStatuses}
        />
      )}
      
      <EditTaskForm
        isOpen={!!editingTask}
        onClose={() => setEditingTask(null)}
        onSubmit={handleUpdateTask}
        task={editingTask}
        loading={loading}
      />
    </>
  );
}
