'use client';

import { useState } from 'react';
import { KanbanBoard } from './Board';
import { EditTaskForm } from '@/components/forms/EditTaskForm';
import { useTasks } from '@/hooks/useTasks';
import { Task, TaskStatus } from '@/lib/types';
import { UpdateTaskData } from '@/clients/tasks-client';

interface BoardContainerProps {
  initialTasks: Task[];
  initialStats: {
    total: number;
    completed: number;
    inProgress: number;
    todo: number;
    completionRate: number;
  };
}

export function KanbanBoardContainer({ initialTasks, initialStats }: BoardContainerProps) {
  const { tasks, loading, syncing, createTask, deleteTask, updateTask, updateTaskOptimistic } = useTasks(
    { limit: 20 }, 
    { tasks: initialTasks, stats: initialStats }
  );

  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
    });
  };

  return (
    <>
      <KanbanBoard 
        tasks={tasks}
        onCreateTask={createTask}
        onDeleteTask={deleteTask}
        onEditTask={handleEditTask}
        onUpdateTitle={handleUpdateTitle}
        onUpdateStatus={handleUpdateStatus}
        loading={loading}
      />
      
      <EditTaskForm
        isOpen={!!editingTask}
        onClose={() => setEditingTask(null)}
        onSubmit={handleUpdateTask}
        task={editingTask}
        loading={loading}
      />
    </>
  );
}
