import { createCode } from "supertokens-web-js/recipe/passwordless";
import { useMutation } from "@tanstack/react-query";
import { useNavigate } from "@tanstack/react-router";
import toast from '@/lib/sonner'
import { useLingui } from "@lingui/react/macro";

const useCreateCode = () => {
  const navigate = useNavigate();
  const { t } = useLingui();

  return useMutation({
    mutationFn: (phoneNumber: string) => createCode({ phoneNumber: '+1' + phoneNumber }),
    onSuccess: (data, phoneNumber) => {
      if (data.status === 'OK') {
        toast.success(t`Code sent successfully`);
        navigate({ to: '/login', search: { stage: 'code', number: phoneNumber } });
      } else {
        toast.error(data.reason);
      }
    },
    onError: (error: any) => {
      if (error.isSuperTokensGeneralError === true) {
        toast.error(error.message);
      } else {
        toast.error(t`An unexpected error occurred when trying to send a one-time passcode. Please try again later.`);
      }
    },
  });
};

export default useCreateCode;
