import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// @ts-nocheck
import { PASSWORD_MAX_LENGTH, PASSWORD_MIN_LENGTH } from '$constants';
import { getApolloErrorCode } from '%apolloErrorImports';
import { graphql } from '%graphqlImports';
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, InputFieldController, } from '%reactComponentsImports';
import { logAndFormatError, logError } from '%reactErrorImports';
import { userSessionClient } from '%reactSessionImports';
import { useMutation } from '@apollo/client/react';
import { zodResolver } from '@hookform/resolvers/zod';
import { createFileRoute, Link, redirect, useNavigate, } from '@tanstack/react-router';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
export const Route = createFileRoute('/auth_/register')({
    validateSearch: z.object({
        return_to: z
            .string()
            .refine((v) => v.startsWith('/') && !v.startsWith('//'))
            .optional(),
    }),
    component: RegisterPage,
    beforeLoad: ({ search: { return_to }, context: { userId } }) => {
        if (userId) {
            throw redirect({ to: return_to ?? '/' });
        }
    },
});
const formSchema = z.object({
    email: z.email().transform((value) => value.toLowerCase()),
    password: z.string().min(PASSWORD_MIN_LENGTH).max(PASSWORD_MAX_LENGTH),
});
const registerWithEmailPasswordMutation = graphql(`
  mutation RegisterWithEmailPassword($input: RegisterWithEmailPasswordInput!) {
    registerWithEmailPassword(input: $input) {
      session {
        userId
      }
    }
  }
`);
function RegisterPage() {
    const { control, handleSubmit, setError: setFormError, } = useForm({
        resolver: zodResolver(formSchema),
        reValidateMode: 'onBlur',
    });
    const [registerWithEmailPassword, { loading }] = useMutation(registerWithEmailPasswordMutation);
    const navigate = useNavigate();
    const { return_to } = Route.useSearch();
    const onSubmit = (data) => {
        registerWithEmailPassword({
            variables: {
                input: {
                    email: data.email,
                    password: data.password,
                },
            },
        })
            .then(({ data }) => {
            if (!data) {
                throw new Error('No data returned from login mutation');
            }
            const { userId } = data.registerWithEmailPassword.session;
            userSessionClient.signIn(userId);
            navigate({ to: return_to ?? '/', replace: true }).catch(logError);
        })
            .catch((err) => {
            const errorCode = getApolloErrorCode(err, ['email-taken']);
            switch (errorCode) {
                case 'email-taken': {
                    setFormError('email', { message: 'Email already taken' }, { shouldFocus: true });
                    break;
                }
                default: {
                    toast.error(logAndFormatError(err, 'Sorry, we could not register you.'));
                }
            }
        });
    };
    return (_jsxs(Card, { children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { children: "Register to your account" }), _jsx(CardDescription, { children: "Enter your email below to register for an account" })] }), _jsx(CardContent, { children: _jsxs("form", { onSubmit: handleSubmit(onSubmit), children: [_jsxs("div", { className: "flex flex-col gap-6", children: [_jsx(InputFieldController, { control: control, name: "email", type: "email", autoComplete: "email", placeholder: "user@example.com" }), _jsx(InputFieldController, { control: control, name: "password", type: "password", autoComplete: "new-password", placeholder: "Password" }), _jsx(Button, { type: "submit", className: "w-full", disabled: loading, children: "Register" })] }), _jsxs("div", { className: "mt-4 text-center text-sm", children: ["Already have an account?", ' ', _jsx(Link, { to: "/auth/login", className: "underline underline-offset-4", children: "Login" })] })] }) })] }));
}
//# sourceMappingURL=register.js.map