import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// @ts-nocheck
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_/login')({
    validateSearch: z.object({
        return_to: z
            .string()
            .regex(/^\/[a-zA-Z0-9\-._~!$&'()*+,;=:@?/]*$/)
            .optional(),
    }),
    component: LoginPage,
    beforeLoad: ({ search: { return_to }, context: { userId } }) => {
        if (userId) {
            throw redirect({ to: return_to ?? '/' });
        }
    },
});
const PASSWORD_MIN_LENGTH = 8;
const formSchema = z.object({
    email: z.email().transform((value) => value.toLowerCase()),
    password: z.string().min(PASSWORD_MIN_LENGTH),
});
const loginWithEmailPasswordMutation = graphql(`
  mutation LoginWithEmailPassword($input: LoginWithEmailPasswordInput!) {
    loginWithEmailPassword(input: $input) {
      session {
        userId
      }
    }
  }
`);
function LoginPage() {
    const { control, handleSubmit, resetField, setError: setFormError, } = useForm({
        resolver: zodResolver(formSchema),
        reValidateMode: 'onBlur',
    });
    const [loginWithEmailPassword, { loading }] = useMutation(loginWithEmailPasswordMutation);
    const navigate = useNavigate();
    const { return_to } = Route.useSearch();
    const onSubmit = (data) => {
        loginWithEmailPassword({
            variables: {
                input: {
                    email: data.email,
                    password: data.password,
                },
            },
        })
            .then(({ data }) => {
            if (!data) {
                throw new Error('No data returned from login mutation');
            }
            const { userId } = data.loginWithEmailPassword.session;
            userSessionClient.signIn(userId);
            navigate({ to: return_to ?? '/', replace: true }).catch(logError);
        })
            .catch((err) => {
            const errorCode = getApolloErrorCode(err, [
                'invalid-email',
                'invalid-password',
            ]);
            switch (errorCode) {
                case 'invalid-email': {
                    setFormError('email', { message: 'Email not found' }, { shouldFocus: true });
                    break;
                }
                case 'invalid-password': {
                    resetField('password');
                    setFormError('password', { message: 'Password is incorrect' }, { shouldFocus: true });
                    break;
                }
                default: {
                    toast.error(logAndFormatError(err, 'Sorry, we could not log you in.'));
                }
            }
        });
    };
    return (_jsxs(Card, { children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { children: "Login to your account" }), _jsx(CardDescription, { children: "Enter your email below to login to your 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: "current-password", placeholder: "Password" }), _jsx(Button, { type: "submit", className: "w-full", disabled: loading, children: "Login" })] }), _jsxs("div", { className: "mt-4 text-center text-sm", children: ["Don't have an account?", ' ', _jsx(Link, { to: "/auth/register", className: "underline underline-offset-4", children: "Sign up" })] })] }) })] }));
}
//# sourceMappingURL=login.js.map