import { useQuery, useMutation, useQueryClient, keepPreviousData } from "@tanstack/react-query";
import { listTasks, createTask, updateTask, deleteTask } from "../api";
import type { Task } from "../types";
import { queryKeys } from "../queryKeys";
import { playSound } from "../usePeonSounds";

export function useTaskList(
  projectId: string | undefined,
  status?: string,
  priority?: string
) {
  return useQuery({
    queryKey: queryKeys.tasks.list(projectId!, status, priority),
    queryFn: () => listTasks(projectId!, status || undefined, priority || undefined),
    enabled: !!projectId,
    placeholderData: keepPreviousData,
  });
}

export function useCreateTask(projectId: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: {
      title: string;
      description?: string;
      priority?: string;
      status?: string;
      commit_base?: string;
      commit_head?: string;
    }) => createTask(projectId, data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["tasks", projectId] });
      qc.invalidateQueries({ queryKey: queryKeys.projects.stats(projectId) });
      playSound("work-work");
    },
    onError: () => {
      playSound("hmm");
    },
  });
}

export function useUpdateTask(projectId: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({
      id,
      data,
    }: {
      id: number;
      data: Partial<Pick<Task, "title" | "description" | "priority" | "status" | "commit_base" | "commit_head">>;
    }) => updateTask(id, data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["tasks", projectId] });
      qc.invalidateQueries({ queryKey: queryKeys.projects.stats(projectId) });
      playSound("zug-zug");
    },
    onError: () => {
      playSound("hmm");
    },
  });
}

export function useDeleteTask(projectId: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: number) => deleteTask(id),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["tasks", projectId] });
      qc.invalidateQueries({ queryKey: queryKeys.projects.stats(projectId) });
      playSound("death");
    },
    onError: () => {
      playSound("hmm");
    },
  });
}
