'use client';

import { useState, useEffect, useCallback } from 'react';
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';
import { KanbanHeader } from './KanbanHeader';
import { BoardRouter } from './BoardRouter';

interface KanbanBoardContainerProps {
  showFilters?: boolean;
  showObjectives?: boolean;
  initialTaskIdToEdit?: string | null;
}

export function KanbanBoardContainer({
  showFilters = true,
  showObjectives = true,
  initialTaskIdToEdit = null,
}: 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);

  // Callback memoized pour appliquer le filtre de recherche
  const applyTaskFilter = useCallback(
    (taskToEdit: Task) => {
      if (kanbanFilters.search !== taskToEdit.title) {
        setKanbanFilters({
          ...kanbanFilters,
          search: taskToEdit.title,
        });

        // Nettoyer l'URL pour éviter les répétitions
        if (typeof window !== 'undefined') {
          const url = new URL(window.location.href);
          url.searchParams.delete('taskId');
          window.history.replaceState({}, '', url.toString());
        }
      }
    },
    [kanbanFilters, setKanbanFilters]
  );

  // Effet pour appliquer un filtre de recherche si un taskId est fourni dans l'URL
  useEffect(() => {
    if (initialTaskIdToEdit && filteredTasks.length > 0) {
      const taskToEdit = filteredTasks.find(
        (task) => task.id === initialTaskIdToEdit
      );
      if (taskToEdit) {
        applyTaskFilter(taskToEdit);
      }
    }
  }, [initialTaskIdToEdit, filteredTasks, applyTaskFilter]);

  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 (
    <>
      <KanbanHeader
        showFilters={showFilters}
        showObjectives={showObjectives}
        kanbanFilters={kanbanFilters}
        onFiltersChange={setKanbanFilters}
        preferences={preferences}
        onToggleStatusVisibility={toggleColumnVisibility}
        pinnedTasks={pinnedTasks}
        onEditTask={handleEditTask}
        onUpdateStatus={handleUpdateStatus}
        pinnedTagName={pinnedTagName}
        visibleStatuses={visibleStatuses}
      />

      <BoardRouter
        tasks={filteredTasks}
        kanbanFilters={kanbanFilters}
        onCreateTask={handleCreateTask}
        onEditTask={handleEditTask}
        onUpdateStatus={handleUpdateStatus}
        visibleStatuses={visibleStatuses}
        loading={loading}
      />

      <EditTaskForm
        isOpen={!!editingTask}
        onClose={() => setEditingTask(null)}
        onSubmit={handleUpdateTask}
        task={editingTask}
        loading={loading}
      />
    </>
  );
}
