"use client";

import {
  useInfiniteQuery,
  useMutation,
  useQuery,
  useQueryClient,
} from "@tanstack/react-query";
import { useMemo } from "react";
import { useRouter } from "next/navigation";
import { toast } from "react-toastify";
import { API_ENDPOINTS } from "@/lib/api";
import { customersService } from "@/lib/api/services/customers-service";

export const useCustomersInfiniteQuery = (params?: Record<string, any>) => {
  const queryKey = useMemo(
    () => [API_ENDPOINTS.CUSTOMERS.READ_ALL, params],
    [params],
  );

  return useInfiniteQuery({
    queryKey,

    queryFn: ({ pageParam = 0 }) =>
      customersService.getCustomers({ ...params, offset: pageParam }),

    initialPageParam: 0,

    getNextPageParam: (lastPage) => {
      if (!lastPage.meta) return;
      const { offset, limit, total } = lastPage.meta;

      const nextOffset = offset + limit;

      return nextOffset < total ? nextOffset : undefined;
    },
  });
};
export const useGetAllCustomers = () => {
  const queryKey = useMemo(() => ["GET ALL CUSTOMERS"], []);
  return useQuery({
    queryKey,
    queryFn: () => customersService.getCustomers(),
  });
};
export const useGetCustomersDetails = (id: string) => {
  const queryKey = useMemo(() => ["GET ALL CUSTOMERS", id], [id]);
  return useQuery({
    queryKey,
    queryFn: () => customersService.customerDetails(id),
  });
};
export const useAssignCompany = (id: string, successCallback?: () => void) => {
  const queryClient = useQueryClient();
  const mutationKey = useMemo(
    () => [API_ENDPOINTS.CUSTOMERS.ASSIGN_COMPANY_TO_CUSTOMER(id)],
    [id],
  );
  return useMutation({
    mutationKey,
    mutationFn: customersService.assignCompanyToCustomer,

    onSuccess: () => {
      toast.success("Selected Companies were assigned");
      queryClient.invalidateQueries({
        queryKey: [API_ENDPOINTS.CUSTOMERS.READ_ALL],
      });

      if (successCallback) {
        successCallback();
      }
    },
  });
};
export const useCreateCustomer = () => {
  const queryClient = useQueryClient();
  const router = useRouter();
  const mutationKey = useMemo(
    () => [API_ENDPOINTS.CUSTOMERS.CREATE, "create"],
    [],
  );
  return useMutation({
    mutationKey,
    mutationFn: customersService.createCustomer,
    onSuccess: () => {
      toast.success("Customer created successfully");
      queryClient.invalidateQueries({
        queryKey: [API_ENDPOINTS.CUSTOMERS.READ_ALL],
      });
      router.push("/customers");
    },
  });
};

export const useUpdateCustomer = (id: string) => {
  const queryClient = useQueryClient();
  const router = useRouter();
  const mutationKey = useMemo(
    () => [API_ENDPOINTS.CUSTOMERS.UPDATE(id), "update"],
    [id],
  );
  return useMutation({
    mutationKey,
    mutationFn: customersService.updateCustomer,
    onSuccess: (response) => {
      toast.success("Customer updated successfully");
      queryClient.invalidateQueries({
        queryKey: [API_ENDPOINTS.CUSTOMERS.READ_ALL],
      });
      router.push("/customers");
    },
  });
};

export const useDeleteCustomerQuery = (successCallback?: () => void) => {
  const queryClient = useQueryClient();
  const mutationKey = useMemo(
    () => [API_ENDPOINTS.CUSTOMERS.DELETE, "delete-customer"],
    [],
  );
  return useMutation({
    mutationKey,
    mutationFn: customersService.deleteCustomer,
    onSuccess: (response) => {
      toast.success(response.data.message);
      if (successCallback) {
        successCallback();
      }
      queryClient.invalidateQueries({
        queryKey: [API_ENDPOINTS.CUSTOMERS.READ_ALL],
      });
    },
  });
};
