'use client';

import { useState, useEffect, useCallback } from 'react';
import { Task } from '@/lib/types';
import { tasksClient } from '@/clients/tasks-client';

interface UseTaskSelectorProps {
  selectedTaskId?: string;
  excludePinnedTasks?: boolean;
}

export function useTaskSelector({
  selectedTaskId,
  excludePinnedTasks = true,
}: UseTaskSelectorProps = {}) {
  const [allTasks, setAllTasks] = useState<Task[]>([]);
  const [tasksLoading, setTasksLoading] = useState(false);
  const [tasksLoaded, setTasksLoaded] = useState(false);
  const [selectedTask, setSelectedTask] = useState<Task | undefined>(undefined);

  // Charger toutes les tâches
  const loadTasks = useCallback(async () => {
    if (tasksLoaded) return;

    setTasksLoading(true);
    try {
      const response = await tasksClient.getTasks();
      setAllTasks(response.data);
      setTasksLoaded(true);
    } catch (error) {
      console.error('Error loading tasks:', error);
    } finally {
      setTasksLoading(false);
    }
  }, [tasksLoaded]);

  // Charger les tâches au montage
  useEffect(() => {
    loadTasks();
  }, [loadTasks]);

  // Mettre à jour la tâche sélectionnée quand selectedTaskId change
  useEffect(() => {
    if (selectedTaskId && tasksLoaded) {
      const task = allTasks.find((t: Task) => t.id === selectedTaskId);
      setSelectedTask(task);
    } else if (!selectedTaskId) {
      setSelectedTask(undefined);
    }
  }, [selectedTaskId, tasksLoaded, allTasks]);

  // Filtrer les tâches selon les options
  const filteredTasks = allTasks.filter((task) => {
    // Exclure les tâches avec des tags marqués comme "objectif principal" si demandé
    if (
      excludePinnedTasks &&
      task.tagDetails &&
      task.tagDetails.some((tag) => tag.isPinned)
    ) {
      return false;
    }
    return true;
  });

  // Fonction pour forcer le rechargement
  const refreshTasks = useCallback(async () => {
    setTasksLoaded(false);
    setAllTasks([]);
    await loadTasks();
  }, [loadTasks]);

  return {
    tasks: filteredTasks,
    selectedTask,
    loading: tasksLoading,
    loaded: tasksLoaded,
    refreshTasks,
  };
}
