import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  CreateThemePayload,
  ThemeItem,
  ThemeResponse,
} from "../types/themeTypes";
import { ThemeService } from "../services/themeService";
import { param } from "jquery";

export interface ThemeParams {
  orderBy?: string;
  take?: number;
  skip?: number;
  order?: string;
}
export const useTheme = (params?: ThemeParams, id?: string) => {
  const queryClient = useQueryClient();
  const { data: singleItem } = useQuery<ThemeItem>({
    queryKey: ["Theme1"],
    queryFn: async () => {
      const resp: ThemeItem = await ThemeService.getItem(id || "");
      return resp;
    },
    enabled: !!id,
  });
  const {
    data: items,
    isLoading,
    error,
    refetch,
  } = useQuery<ThemeResponse>({
    queryKey: ["Theme", params],
    queryFn: async () => {
      const resp: ThemeResponse = await ThemeService.getItems(params!);

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

      if (!createResponse) {
        throw new Error("Failed to create Theme item(s)");
      }

      // Step 2: Upload images (parallel)
      try {
        await Promise.all(
          createResponse
            .filter((item) => item.presigned)
            .map(async (item, i) => {
              try {
                await ThemeService.uploadImage(
                  payload.imageFile,
                  item.presigned!
                );
                await ThemeService.updateUploadStatus(item.id, item.id);
                return item;
              } catch (uploadError) {
                // Rollback this specific item if upload fails
                await ThemeService.deleteItem(item.id);
                throw uploadError; // stops Promise.all
              }
            })
        );
      } catch (error) {
        console.error("One or more uploads failed:", error);
        throw error;
      }

      // Step 3: Return final created data
      return createResponse;
    },

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

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