import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  CreateNewsCategoryPayload,
  NewsCategoryItem,
  NewsCategoryResponse,
} from "../types/newsCategoryType";
import { NewsCategoryService } from "../services/newsCategory";

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

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

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

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

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

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

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

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

  const updateMutation = useMutation({
    mutationFn: async ({
      id,
      data,
      imageFile,
    }: {
      id: string;
      data: Partial<CreateNewsCategoryPayload>;
      imageFile?: File;
    }) => {
      // Step 1: Update the item data
      const updateResponse = await NewsCategoryService.updateItem(id, data);

      // Step 2: If there's a new image file, upload it
      if (imageFile && updateResponse.presigned) {
        try {
          await NewsCategoryService.uploadImage(
            imageFile,
            updateResponse.presigned
          );
        } catch (uploadError) {
          console.error("Image upload failed during update:", uploadError);
          throw uploadError;
        }

        // Step 3: Update upload status to active
        await NewsCategoryService.updateUploadStatus(id, true);
      }

      return updateResponse;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["NewsCategory", params] });
      queryClient.invalidateQueries({ queryKey: ["NewsCategory1", params] });
    },
  });

  const deleteMutation = useMutation({
    mutationFn: NewsCategoryService.deleteItem,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["NewsCategory", params] });
      queryClient.invalidateQueries({ queryKey: ["NewsCategory1", 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: refetchItems, // Use the items refetch function
  };
};
