'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, TaskPriority } from '@/lib/types';
import { CreateTaskData } from '@/clients/tasks-client';
import { updateTask, createTask } from '@/actions/tasks';
import { getAllStatuses } from '@/lib/status-config';

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

export function KanbanBoardContainer({ 
  showFilters = true, 
  showObjectives = true
}: KanbanBoardContainerProps = {}) {
  const { 
    filteredTasks, 
    pinnedTasks,
    loading, 
    updateTaskOptimistic,
    kanbanFilters,
    setKanbanFilters,
    tags,
    refreshTasks
  } = 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: { taskId: string; title?: string; description?: string; status?: TaskStatus; priority?: TaskPriority; tags?: string[]; dueDate?: Date; }) => {
    const result = await updateTask(data);
    if (result.success) {
      await refreshTasks(); // Rafraîchir les données
      setEditingTask(null);
    } else {
      console.error('Error updating task:', result.error);
    }
  };


  const handleUpdateStatus = async (taskId: string, newStatus: TaskStatus) => {
    // Utiliser la mise à jour optimiste pour le drag & drop
    await updateTaskOptimistic(taskId, 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> => {
    const result = await createTask(data);
    if (result.success) {
      await refreshTasks(); // Rafraîchir les données
    } else {
      console.error('Error creating task:', result.error);
    }
  };

  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}
          onEditTask={handleEditTask}
          onUpdateStatus={handleUpdateStatus}
          compactView={kanbanFilters.compactView}
          pinnedTagName={pinnedTagName}
        />
      )}
      
      {kanbanFilters.swimlanesByTags ? (
        kanbanFilters.swimlanesMode === 'priority' ? (
          <PrioritySwimlanesBoard 
            tasks={filteredTasks}
            onCreateTask={handleCreateTask}
            onEditTask={handleEditTask}
            onUpdateStatus={handleUpdateStatus}
            compactView={kanbanFilters.compactView}
            visibleStatuses={visibleStatuses}
            loading={loading}
          />
        ) : (
          <SwimlanesBoard 
            tasks={filteredTasks}
            onCreateTask={handleCreateTask}
            onEditTask={handleEditTask}
            onUpdateStatus={handleUpdateStatus}
            compactView={kanbanFilters.compactView}
            visibleStatuses={visibleStatuses}
            loading={loading}
          />
        )
      ) : (
        <KanbanBoard 
          tasks={filteredTasks}
          onCreateTask={handleCreateTask}
          onEditTask={handleEditTask}
          onUpdateStatus={handleUpdateStatus}
          compactView={kanbanFilters.compactView}
          visibleStatuses={visibleStatuses}
        />
      )}
      
      <EditTaskForm
        isOpen={!!editingTask}
        onClose={() => setEditingTask(null)}
        onSubmit={handleUpdateTask}
        task={editingTask}
        loading={loading}
      />
    </>
  );
}
