import { useQuery, useMutation, useQueryClient, keepPreviousData } from "@tanstack/react-query";
import { listFeatures, createFeature, updateFeature, deleteFeature } from "../api";
import type { Feature } from "../types";
import { queryKeys } from "../queryKeys";
import { playSound } from "../usePeonSounds";

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

export function useCreateFeature(projectId: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: { name: string; description?: string; status?: string }) =>
      createFeature(projectId, data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["features", projectId] });
      qc.invalidateQueries({ queryKey: queryKeys.projects.stats(projectId) });
      playSound("i-can-do-that");
    },
    onError: () => {
      playSound("hmm");
    },
  });
}

export function useUpdateFeature(projectId: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({
      id,
      data,
    }: {
      id: number;
      data: Partial<Pick<Feature, "name" | "description" | "status">>;
    }) => updateFeature(id, data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["features", projectId] });
      qc.invalidateQueries({ queryKey: queryKeys.projects.stats(projectId) });
      playSound("zug-zug");
    },
    onError: () => {
      playSound("hmm");
    },
  });
}

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