import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  CreateSocialMediaPayload,
  SocialMediaItem,
  SocialMediaResponse,
} from "../types/socialMediaType";
import { SocialMediaService } from "../services/socialMediaService";
import { param } from "jquery";

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

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

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

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

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

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

  const updateMutation = useMutation({
    mutationFn: ({
      id,
      data,
    }: {
      id: string;
      data: Partial<CreateSocialMediaPayload>;
    }) => SocialMediaService.updateItem(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["SocialMedia1", params] });
    },
  });

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