import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { CreateNewsPayload, NewsItem, NewsResponse } from "../types/newsTypes";
import { NewsService } from "../services/newsService";

export interface NewsParams {
  orderBy?: string;
  take?: number;
  skip?: number;
  order?: string;
  isActive?: boolean;
  isFeatured?: boolean;
  newsCategoryId?: string;
}

export const useNews = (params?: NewsParams, id?: string) => {
  const queryClient = useQueryClient();

  const {
    data: singleItem,
    isLoading,
    error,
    refetch,
  } = useQuery<NewsItem>({
    queryKey: ["News", id],
    queryFn: async () => {
      const resp: NewsItem = await NewsService.getItem(id || "");
      return resp;
    },
    enabled: !!id,
  });

  const { data: items, refetch: refetchItems } = useQuery<NewsResponse>({
    queryKey: ["News1", params],
    queryFn: async () => {
      const resp: NewsResponse = await NewsService.getItems(params!);
      return resp;
    },
  });

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

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

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

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

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

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

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

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

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

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