import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { PurchaseRepository } from "../repositories/PurchaseRepository";
import showToast from "../services/toastService";

export const usePurchasesList = (
  pageSize,
  pageNumber,
  isActive,
  filter,
  searchString
) => {
  return useQuery({
    queryKey: [
      "purchase_list",
      pageSize,
      pageNumber,
      isActive,
      filter,
      searchString,
    ],
    queryFn: async () => {
      const resp = await PurchaseRepository.GetPurchaseList(
        pageSize,
        pageNumber,
        isActive,
        filter,
        searchString
      );
      return resp.data;
    },
  });
};

export const useDeliverChallane = (purchaseInvoiceId) => {
  return useQuery({
    queryKey: ["deliverliy_challane", purchaseInvoiceId],
    queryFn: async () => {
      const resp = await PurchaseRepository.GetDeliveryChallan(
        purchaseInvoiceId
      );
      return resp.data;
    },
    enabled: !!purchaseInvoiceId,
  });
};

export const usePurchase = (id) => {
  return useQuery({
    queryKey: ["purchase", id],
    queryFn: async () => {
      const resp = await PurchaseRepository.GetPurchase(id);
      return resp.data;
    },
    enabled: !!id,
  });
};

export const usePurchasePaymentHistory = (id) => {
  return useQuery({
    queryKey: ["purchase_payment_history", id],
    queryFn: async () => {
      const resp = await PurchaseRepository.GetPaymentHistory(id);
      return resp.data;
    },
    enabled: !!id,
  });
};

export const useCreatePurchaseInvoice = (onSuccessCallback) => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (payload) =>
      await PurchaseRepository.CreatePurchase(payload),
    onSuccess: (data, variables) => {
      queryClient.invalidateQueries({ queryKey: ["purchase_list"] });
      showToast("Purchase Invoice Created successfully", "success");
      if (onSuccessCallback) onSuccessCallback();
    },
    onError: (error) => {
      showToast(
        error?.response?.data?.message ||
          error.message ||
          "Failed to create invoice",
        "error"
      );
    },
  });
};

export const useUpdatePurchaseInvoice = (onSuccessCallback) => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({ purchaseId, payload }) =>
      PurchaseRepository.UpdatePurchase(purchaseId, payload),
    onSuccess: (data, variables) => {
      queryClient.invalidateQueries({ queryKey: ["purchase_list"] });
      queryClient.invalidateQueries({ queryKey: ["purchase"] });
      showToast("Purchase Invoice Updated successfully", "success");
      if (onSuccessCallback) onSuccessCallback();
    },
    onError: (error) => {
      showToast(
        error?.response?.data?.message ||
          error.message ||
          "Failed to create invoice",
        "error"
      );
    },
  });
};
export const useAddDeliverChallan = (onSuccessCallback) => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (payload) =>
      PurchaseRepository.addDelievryChallan(payload),
    onSuccess: (data, variables) => {
      queryClient.invalidateQueries({ queryKey: ["deliverliy_challane"] });
      showToast("Challan added successfully", "success");
      if (onSuccessCallback) onSuccessCallback();
    },
    onError: (error) => {
      showToast(
        error?.response?.data?.message ||
          error.message ||
          "Failed to create invoice",
        "error"
      );
    },
  });
};
export const useAddPurchasePayment =(onSuccessCallback)=>{
const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (payload) =>
      PurchaseRepository.AddPayment(payload),
    onSuccess: (data, variables) => {
      queryClient.invalidateQueries({ queryKey: ["purchase_payment_history"] });
      showToast("Payment added successfully", "success");
      if (onSuccessCallback) onSuccessCallback();
    },
    onError: (error) => {
      showToast(
        error?.response?.data?.message ||
          error.message ||
          "Failed to Add payment",
        "error"
      );
    },
  });
}


export const useDeletePurchaseInvoice = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({ id, isActive }) =>
      await PurchaseRepository.deletePurchase(id, isActive),

    onSuccess: (_, variable) => {
      queryClient.invalidateQueries({ queryKey: ["purchase_list"] });
      showToast(
        `Purchase Invoice ${variable.isActive ? "restored" : "deleted"} successfully`,
        "success"
      );
    },

    onError: (error) => {
      showToast(
        error?.response?.data?.message ||
          error.message ||
          "Failed to delete branch",
        "error"
      );
    },
  });
};
