import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  CreateContactUsPayload,
  ContactUsItem,
  ContactUsResponse,
} from "../types/contactUs";
import { ContactUsService } from "../services/contactUsService";
import { param } from "jquery";

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

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

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

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

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

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

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

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