import { consumeCode } from "supertokens-web-js/recipe/passwordless";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { fetchMe } from "@/features/players/server";
import { useNavigate } from "@tanstack/react-router";
import toast from '@/lib/sonner'
import { playerKeys } from "@/features/players/queries";
import { useLingui } from "@lingui/react/macro";

const useConsumeCode = (onWrongCode: () => void) => {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { t } = useLingui();

  return useMutation({
    mutationFn: (code: string) => consumeCode({ userInputCode: code }),
    onSuccess: async (data) => {
      if (data.status === 'OK') {
        const response = await fetchMe();
        if (!response.success || !response.data.user) {
          navigate({ to: '/login', search: { stage: 'name' } });
        } else {
          queryClient.setQueryData(playerKeys.auth, response.data);
          toast.success(t`Successfully logged in. Welcome back!`);
          navigate({ to: '/' })
        }
      } else if (data.status === 'INCORRECT_USER_INPUT_CODE_ERROR') {
        onWrongCode();
      } else if (data.status === 'EXPIRED_USER_INPUT_CODE_ERROR') {
        toast.error(t`Code has expired. Please request a new code.`);
      } else if (data.status === "RESTART_FLOW_ERROR") {
        toast.error(t`Too many failed attempts. Please try again.`);
        navigate({ to: '/login', search: { stage: undefined, number: undefined } });
      } else {
        toast.error(t`Unknown error. Please try again later.`);
      }

      return data;
    },
    onError: (error: any) => {
      if (error.isSuperTokensGeneralError === true) {
        toast.error(error.message);
      } else {
        toast.error(t`Unknown error. Please try again later.`);
      }
    },
  });
};

export default useConsumeCode;
