import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  CreateModulesPayload,
  ModulesItem,
  ModulesResponse,
} from "../types/modulesType";
import { ModulesService } from "../services/modulesService";
import { param } from "jquery";

export interface ModulesParams {
  orderBy?: string;
  take?: number;
  skip?: number;
  order?: string;
  isActive?: boolean;
}
export const useModules = (params?: ModulesParams, id?: string) => {
  const queryClient = useQueryClient();

  const {
    data: singleItem,
    isLoading,
    error,
  } = useQuery<ModulesItem>({
    queryKey: ["Modules", id],
    queryFn: async () => {
      const resp: ModulesItem = await ModulesService.getItem(id || "");

      return resp;
    },
    enabled: !!id,
  });
  const { data: items, refetch } = useQuery<ModulesResponse>({
    queryKey: ["Modules1", params],
    queryFn: async () => {
      const resp: ModulesResponse = await ModulesService.getItems(params!);

      return resp;
    },
  });
  const createMutation = useMutation({
    mutationFn: async (payload: { data: CreateModulesPayload }) => {
      // Step 1: Create the initial item record
      const createResponse = await ModulesService.createItem(payload.data);

      if (!createResponse.id) {
        throw new Error("Failed to create Modules item");
      }

      return createResponse;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["Modules1", params],
      });
    },
  });

  const updateMutation = useMutation({
    mutationFn: ({
      id,
      data,
    }: {
      id: string;
      data: Partial<CreateModulesPayload>;
    }) => ModulesService.updateItem(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["Modules1", params] });
    },
  });

  const deleteMutation = useMutation({
    mutationFn: ModulesService.deleteItem,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["Modules1", params] });
    },
  });
  return {
    items: items?.items,
    singleItem: singleItem,
    count: items?.count,
    isLoading,
    error,
    createItem: createMutation.mutateAsync,
    updateItem: updateMutation.mutateAsync,
    deleteItem: deleteMutation.mutateAsync,
    isCreating: createMutation.isPending,
    isUpdating: updateMutation.isPending,
    isDeleting: deleteMutation.isPending,
    refetch,
  };
};
