import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  CreateMessagePayload,
  MessageItem,
  MessageResponse,
} from "../types/messageTypes";
import { MessageService } from "../services/messageService";
import { param } from "jquery";

export interface MessageParams {
  orderBy?: string;
  take?: number;
  skip?: number;
  order?: string;
  isActive?: boolean;
}
export const useMessage = (params?: MessageParams, id?: string) => {
  const queryClient = useQueryClient();
  const { data: singleItem } = useQuery<MessageItem>({
    queryKey: ["Message",id],
    queryFn: async () => {
      const resp: MessageItem = await MessageService.getItem(id || "");
      return resp;
    },
    enabled: !!id,
  });
  const {
    data: items,
    isLoading,
    error,
    refetch,
  } = useQuery<MessageResponse>({
    queryKey: ["Message1", params],
    queryFn: async () => {
      const resp: MessageResponse = await MessageService.getItems(params!);

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

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

      // Step 2: Upload the image file

      try {
        await MessageService.uploadImage(
          payload.imageFile,
          createResponse.presigned!
        );
      } catch (uploadError) {
        // Rollback creation if upload fails
        await MessageService.deleteItem(createResponse.id);
        throw uploadError;
      }

      // Step 3: Update status to active
      await MessageService.updateUploadStatus(
        createResponse.id,
        true
      );

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

  const updateMutation = useMutation({
    mutationFn: async ({
      id,
      data,
      imageFile,
    }: {
      id: string;
      data: Partial<CreateMessagePayload>;
      imageFile?: File | null;
    }) => {
      // 1️⃣ Update the basic message data first
      const updateResponse = await MessageService.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 MessageService.uploadImage(
            imageFile,
            presignedResponse.presigned!
          );
        } catch (uploadError) {
          console.error("Image upload failed:", uploadError);
          throw uploadError;
        }
        await MessageService.updateUploadStatus(id, true);
      }

      return updateResponse;
    },

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

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