import { useMutation, useIsMutating } from '@tanstack/react-query';
import { useWidget } from './useWidget';

import type { MutationKey, UseMutationOptions } from '@tanstack/react-query';

const useSendMagicLink = (
	_options?: UseMutationOptions<
		unknown,
		unknown,
		WidgetProvider.SendMagicLinkOptions
	>
) => {
	const { sendMagicLink } = useWidget();

	const mutationKey: MutationKey = ['login', 'magic_link', 'email'];
	const isLoading = useIsMutating(mutationKey) > 0;

	const options = {
		mutationKey,
		mutationFn: (params) => sendMagicLink(params),
		..._options,
	} as UseMutationOptions<
		unknown,
		unknown,
		WidgetProvider.SendMagicLinkOptions
	>;

	const mutation = useMutation(options);

	return { ...mutation, isLoading };
};

export default useSendMagicLink;
