'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api';
import type { TodoistTask, TodoistProject, TodoistPriority } from '@/types/integrations';

/** Query key factory */
export const tasksKeys = {
  all: ['tasks'] as const,
  list: (filters?: { projectId?: string; dueToday?: boolean }) =>
    [...tasksKeys.all, 'list', filters] as const,
  projects: ['tasks', 'projects'] as const,
  detail: (id: string) => [...tasksKeys.all, 'detail', id] as const,
};

interface FetchTasksParams {
  projectId?: string;
  dueToday?: boolean;
}

/**
 * Fetch Todoist tasks
 */
async function fetchTasks(params?: FetchTasksParams): Promise<TodoistTask[]> {
  const queryParams: Record<string, string | number | boolean | undefined> = {};
  if (params?.projectId) queryParams.projectId = params.projectId;
  if (params?.dueToday) queryParams.dueToday = true;

  const response = await api.get<{ tasks: TodoistTask[] } | TodoistTask[]>(
    '/integrations/todoist/tasks',
    { params: queryParams },
  );
  return Array.isArray(response) ? response : response.tasks;
}

/**
 * Fetch Todoist projects
 */
async function fetchProjects(): Promise<TodoistProject[]> {
  const response = await api.get<{ projects: TodoistProject[] } | TodoistProject[]>(
    '/integrations/todoist/projects',
  );
  return Array.isArray(response) ? response : response.projects;
}

/**
 * Complete a task
 */
async function completeTask(taskId: string): Promise<void> {
  await api.post(`/integrations/todoist/tasks/${taskId}/complete`);
}

/**
 * Create a new task
 */
async function createTask(params: {
  content: string;
  description?: string;
  projectId?: string;
  priority?: TodoistPriority;
  dueString?: string;
}): Promise<TodoistTask> {
  return api.post<TodoistTask>('/integrations/todoist/tasks', params);
}

/**
 * Hook to fetch Todoist tasks
 */
export function useTasks(params?: FetchTasksParams) {
  return useQuery({
    queryKey: tasksKeys.list(params),
    queryFn: () => fetchTasks(params),
    staleTime: 30 * 1000,
    refetchOnWindowFocus: true,
  });
}

/**
 * Hook to fetch today's tasks
 */
export function useTodaysTasks() {
  return useTasks({ dueToday: true });
}

/**
 * Hook to fetch Todoist projects
 */
export function useProjects() {
  return useQuery({
    queryKey: tasksKeys.projects,
    queryFn: fetchProjects,
    staleTime: 60 * 1000,
  });
}

/**
 * Hook to complete a task
 */
export function useCompleteTask() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: completeTask,
    onMutate: async (taskId) => {
      await queryClient.cancelQueries({ queryKey: tasksKeys.all });

      queryClient.setQueriesData<TodoistTask[]>(
        { queryKey: tasksKeys.all },
        (old) => old?.map((task) =>
          task.id === taskId ? { ...task, isCompleted: true } : task
        )
      );
    },
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: tasksKeys.all });
    },
  });
}

/**
 * Hook to create a task
 */
export function useCreateTask() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: createTask,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: tasksKeys.all });
    },
  });
}
