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, } from '%reactComponentsImports';
import { logAndFormatError, logError } from '%reactErrorImports';
import { useMutation } from '@apollo/client/react';
import { createFileRoute, redirect, useNavigate } from '@tanstack/react-router';
import { useCallback, useEffect, useState } from 'react';
import { toast } from 'sonner';
import { z } from 'zod';
export const Route = createFileRoute('/auth_/verify-email')({
    validateSearch: z.object({
        token: z.string().optional(),
    }),
    component: VerifyEmailPage,
    beforeLoad: ({ search: { token } }) => {
        if (!token) {
            throw redirect({ to: '/' });
        }
    },
});
const verifyEmailMutation = graphql(`
  mutation VerifyEmail($input: VerifyEmailInput!) {
    verifyEmail(input: $input) {
      success
    }
  }
`);
const requestEmailVerificationMutation = graphql(`
  mutation RequestEmailVerification {
    requestEmailVerification {
      success
    }
  }
`);
function VerifyEmailPage() {
    const { token } = Route.useSearch();
    const { userId } = Route.useRouteContext();
    const navigate = useNavigate();
    const [status, setStatus] = useState(userId ? 'verifying' : 'idle');
    const [verifyEmail] = useMutation(verifyEmailMutation);
    const [requestVerification, { loading: resending }] = useMutation(requestEmailVerificationMutation);
    const doVerify = useCallback(() => {
        if (!token)
            return;
        setStatus('verifying');
        verifyEmail({
            variables: { input: { token } },
        })
            .then(() => {
            setStatus('success');
        })
            .catch((err) => {
            const errorCode = getApolloErrorCode(err, [
                'invalid-token',
                'token-expired',
            ]);
            switch (errorCode) {
                case 'invalid-token':
                case 'token-expired': {
                    setStatus('error');
                    break;
                }
                default: {
                    toast.error(logAndFormatError(err, 'Sorry, we could not verify your email.'));
                    setStatus('error');
                }
            }
        });
    }, [token, verifyEmail]);
    // If logged in, auto-verify on mount
    useEffect(() => {
        if (userId && token) {
            doVerify();
        }
    }, [userId, token, doVerify]);
    const handleResend = () => {
        requestVerification()
            .then(() => {
            toast.success('Verification email sent! Check your inbox.');
        })
            .catch((err) => {
            toast.error(logAndFormatError(err, 'Could not resend verification email.'));
        });
    };
    // Verifying state
    if (status === 'verifying') {
        return (_jsx(Card, { children: _jsxs(CardHeader, { children: [_jsx(CardTitle, { children: "Verifying..." }), _jsx(CardDescription, { children: "Please wait while we verify your email address." })] }) }));
    }
    // Success state
    if (status === 'success') {
        return (_jsxs(Card, { children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { children: "Email Verified!" }), _jsx(CardDescription, { children: "Your email address has been successfully verified." })] }), _jsx(CardContent, { children: _jsx(Button, { variant: "secondary", className: "w-full", onClick: () => {
                            navigate({ to: '/' }).catch(logError);
                        }, children: "Continue" }) })] }));
    }
    // Error state
    if (status === 'error') {
        return (_jsxs(Card, { children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { children: "Invalid or Expired Link" }), _jsx(CardDescription, { children: "This verification link is invalid or has expired." })] }), _jsx(CardContent, { children: _jsx("div", { className: "flex flex-col gap-3", children: userId ? (_jsx(Button, { variant: "secondary", className: "w-full", disabled: resending, onClick: handleResend, children: "Resend Verification Email" })) : (_jsx(Button, { variant: "secondary", className: "w-full", onClick: () => {
                                navigate({ to: '/auth/login' }).catch(logError);
                            }, children: "Log In to Resend" })) }) })] }));
    }
    // Idle state (not logged in) — show button to verify
    return (_jsxs(Card, { children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { children: "Verify your email" }), _jsx(CardDescription, { children: "Click the button below to verify your email address." })] }), _jsx(CardContent, { children: _jsx(Button, { className: "w-full", onClick: doVerify, children: "Verify Email" }) })] }));
}
//# sourceMappingURL=verify-email.js.map