import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { CreateGoalPayload, GoalItem, GoalResponse } from "../types/goalType";
import { GoalService } from "../services/goalService";
import { param } from "jquery";

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

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

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

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

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

      // Step 2: Upload the image file
      try {
        await GoalService.uploadImage(
          payload.imageFile,
          createResponse.presigned!
        );
      } catch (uploadError) {
        // Rollback creation if upload fails
        await GoalService.deleteItem(createResponse.id);
        throw uploadError;
      }

      // Step 3: Update status to active
      await GoalService.changeStatus(createResponse?.id);

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

  const updateMutation = useMutation({
    mutationFn: async ({
      id,
      data,
      imageFile,
    }: {
      id: string;
      data: Partial<CreateGoalPayload>;
      imageFile?: File | null;
    }) => {
      // 1️⃣ Update the basic message data first
      const updateResponse = await GoalService.updateItem(id, data);

      // 2️⃣ If a new image file is selected, handle image upload
      if (imageFile) {
        try {
          // Request new presigned URL
          const presignedResponse = updateResponse;

          // Upload the new image
          await GoalService.uploadImage(
            imageFile,
            presignedResponse.presigned!
          );
        } catch (uploadError) {
          console.error("Image upload failed:", uploadError);
          throw uploadError;
        }
        await GoalService.changeStatus(id);
      }

      return updateResponse;
    },

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

  const deleteMutation = useMutation({
    mutationFn: (id: string) => GoalService.deleteItem(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["Goal1", 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,
  };
};
