import { useUser } from "@/contexts";
import { API_ENDPOINTS, userService } from "@/lib/api";
import {
  useInfiniteQuery,
  useMutation,
  useQuery,
  useQueryClient,
} from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { useMemo } from "react";
import { toast } from "react-toastify";

export const useLoginQuery = () => {
  const mutationKey = useMemo(() => [API_ENDPOINTS.USER.LOGIN], []);
  const { setAuthState } = useUser();
  const router = useRouter();
  return useMutation({
    mutationKey,
    mutationFn: userService.login,
    onSuccess: (response) => {
      if (response.success) {
        setAuthState(response.data);
        router.replace("/charts");
      }
    },
  });
};

export const useDeleteAdmin = (onSuccessCallback: () => void) => {
  const queryClient = useQueryClient();
  const mutationKey = useMemo(() => [API_ENDPOINTS.USER.ADMINS, "delete"], []);
  return useMutation({
    mutationKey,
    mutationFn: userService.deleteAdmin,
    onSuccess: (response) => {
      toast.info(response.data.message);
      onSuccessCallback();
      queryClient.invalidateQueries({
        queryKey: [API_ENDPOINTS.USER.ADMINS],
      });
    },
  });
};
export const useLogoutQuery = () => {
  const queryKey = useMemo(() => [API_ENDPOINTS.USER.LOGOUT], []);

  return useQuery({
    queryKey,
    queryFn: userService.logout,
  });
};

export const useCreateAdmin = () => {
  const queryClient = useQueryClient();
  const router = useRouter();
  const mutationKey = useMemo(() => [API_ENDPOINTS.USER.ADMINS, "create"], []);
  return useMutation({
    mutationKey,
    mutationFn: userService.createAdmin,
    onSuccess: (response) => {
      toast.success(response);
      queryClient.invalidateQueries({
        queryKey: [API_ENDPOINTS.USER.ADMINS],
      });
      router.push("/admins");
    },
  });
};

export const useUpdateAdmin = (id: string) => {
  const queryClient = useQueryClient();
  const router = useRouter();
  const mutationKey = useMemo(
    () => [API_ENDPOINTS.USER.ADMINS, "update", id],
    [id],
  );
  return useMutation({
    mutationKey,
    mutationFn: userService.updateAdmin,
    onSuccess: (response) => {
      toast.success(response);
      queryClient.invalidateQueries({
        queryKey: [API_ENDPOINTS.USER.ADMINS],
      });
      router.push("/admins");
    },
  });
};

export const useAdminDetails = (id: string) => {
  const queryKey = useMemo(
    () => [API_ENDPOINTS.USER.ADMINS, "details", id],
    [id],
  );
  return useQuery({
    queryKey,
    queryFn: () => userService.adminDetails(id),
  });
};

export const useAdminListInfiniteQuery = (params?: Record<string, any>) => {
  const queryKey = useMemo(() => [API_ENDPOINTS.USER.ADMINS, params], [params]);

  return useInfiniteQuery({
    queryKey,

    queryFn: ({ pageParam = 0 }) =>
      userService.adminsList({ ...params, offset: pageParam }),

    initialPageParam: 0,

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

      const nextOffset = offset + limit;

      return nextOffset < total ? nextOffset : undefined;
    },
  });
};
export const useChangeAdminStatus = ({
  id,
  successCallback,
}: {
  id: string;
  successCallback: () => void;
}) => {
  const queryClient = useQueryClient();
  const mutationKey = useMemo(
    () => [API_ENDPOINTS.USER.CHANGE_ADMIN_STATUS(id)],
    [id],
  );
  return useMutation({
    mutationKey,
    mutationFn: userService.changeAdminStatus,
    onSuccess: ({ message }: { message: string }) => {
      successCallback();
      toast.success(message);
      queryClient.invalidateQueries({
        queryKey: [API_ENDPOINTS.USER.ADMINS],
      });
    },
  });
};
