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 { useMutation } from '@apollo/client/react';
import { zodResolver } from '@hookform/resolvers/zod';
import { createFileRoute, Link, redirect, useNavigate, } from '@tanstack/react-router';
import { useCallback, useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
export const Route = createFileRoute('/auth_/reset-password')({
    validateSearch: z.object({
        token: z.string().optional(),
    }),
    component: ResetPasswordPage,
    beforeLoad: ({ search: { token }, context: { userId } }) => {
        if (userId) {
            throw redirect({ to: '/' });
        }
        if (!token) {
            throw redirect({ to: '/auth/forgot-password' });
        }
    },
});
const formSchema = z
    .object({
    newPassword: z.string().min(PASSWORD_MIN_LENGTH).max(PASSWORD_MAX_LENGTH),
    confirmPassword: z
        .string()
        .min(PASSWORD_MIN_LENGTH)
        .max(PASSWORD_MAX_LENGTH),
})
    .refine((data) => data.newPassword === data.confirmPassword, {
    message: 'Passwords do not match',
    path: ['confirmPassword'],
});
const validateTokenMutation = graphql(`
  mutation ValidatePasswordResetToken(
    $input: ValidatePasswordResetTokenInput!
  ) {
    validatePasswordResetToken(input: $input) {
      success
    }
  }
`);
const resetPasswordMutation = graphql(`
  mutation ResetPasswordWithToken($input: ResetPasswordWithTokenInput!) {
    resetPasswordWithToken(input: $input) {
      success
    }
  }
`);
function ResetPasswordPage() {
    const { token } = Route.useSearch();
    const navigate = useNavigate();
    const [tokenValid, setTokenValid] = useState(null);
    const [validationError, setValidationError] = useState(null);
    const [resetComplete, setResetComplete] = useState(false);
    const [validateToken] = useMutation(validateTokenMutation);
    const [resetPassword, { loading }] = useMutation(resetPasswordMutation);
    const { control, handleSubmit } = useForm({
        resolver: zodResolver(formSchema),
        reValidateMode: 'onBlur',
    });
    const runTokenValidation = useCallback(() => {
        if (!token)
            return;
        setTokenValid(null);
        setValidationError(null);
        validateToken({
            variables: { input: { token } },
        })
            .then(() => {
            setTokenValid(true);
        })
            .catch((err) => {
            const errorCode = getApolloErrorCode(err, ['invalid-token']);
            switch (errorCode) {
                case 'invalid-token': {
                    setTokenValid(false);
                    break;
                }
                default: {
                    setValidationError(logAndFormatError(err, 'Sorry, we could not validate your reset link.'));
                }
            }
        });
    }, [token, validateToken]);
    // Validate token on mount
    useEffect(() => {
        runTokenValidation();
    }, [runTokenValidation]);
    const onSubmit = (data) => {
        if (!token)
            return;
        resetPassword({
            variables: {
                input: {
                    token,
                    newPassword: data.newPassword,
                },
            },
        })
            .then(() => {
            setResetComplete(true);
            toast.success('Password reset successful!');
        })
            .catch((err) => {
            const errorCode = getApolloErrorCode(err, [
                'invalid-token',
                'token-expired',
            ]);
            switch (errorCode) {
                case 'invalid-token':
                case 'token-expired': {
                    setTokenValid(false);
                    break;
                }
                default: {
                    toast.error(logAndFormatError(err, 'Sorry, we could not reset your password.'));
                }
            }
        });
    };
    // Loading state
    if (tokenValid === null && !validationError) {
        return (_jsx(Card, { children: _jsxs(CardHeader, { children: [_jsx(CardTitle, { children: "Validating..." }), _jsx(CardDescription, { children: "Please wait while we verify your reset link." })] }) }));
    }
    // Validation error state (transient failures, not invalid token)
    if (validationError) {
        return (_jsxs(Card, { children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { children: "Something Went Wrong" }), _jsx(CardDescription, { children: validationError })] }), _jsx(CardContent, { children: _jsx(Button, { variant: "secondary", className: "w-full", onClick: runTokenValidation, children: "Try Again" }) })] }));
    }
    // Invalid token state
    if (!tokenValid) {
        return (_jsxs(Card, { children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { children: "Invalid or Expired Link" }), _jsx(CardDescription, { children: "This password reset link is invalid or has expired. Please request a new one." })] }), _jsx(CardContent, { children: _jsx(Link, { to: "/auth/forgot-password", children: _jsx(Button, { variant: "secondary", className: "w-full", children: "Request New Link" }) }) })] }));
    }
    // Success state - redirect to login
    if (resetComplete) {
        return (_jsxs(Card, { children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { children: "Password Reset Complete" }), _jsx(CardDescription, { children: "Your password has been successfully reset. You can now log in with your new password." })] }), _jsx(CardContent, { children: _jsx(Button, { variant: "secondary", className: "w-full", onClick: () => {
                            navigate({ to: '/auth/login' }).catch(logError);
                        }, children: "Go to Login" }) })] }));
    }
    // Reset form
    return (_jsxs(Card, { children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { children: "Reset your password" }), _jsx(CardDescription, { children: "Enter your new password below." })] }), _jsx(CardContent, { children: _jsx("form", { onSubmit: handleSubmit(onSubmit), children: _jsxs("div", { className: "flex flex-col gap-6", children: [_jsx(InputFieldController, { control: control, name: "newPassword", label: "New Password", type: "password", autoComplete: "new-password", placeholder: "Enter new password" }), _jsx(InputFieldController, { control: control, name: "confirmPassword", label: "Confirm Password", type: "password", autoComplete: "new-password", placeholder: "Confirm new password" }), _jsx(Button, { type: "submit", className: "w-full", disabled: loading, children: "Reset Password" })] }) }) })] }));
}
//# sourceMappingURL=reset-password.js.map