import { useLingui } from '../../../../../../node_modules/@lingui/react/dist/index.mjs';
import React__default from 'react';
import { getTranslatedError } from '../../../utils/getTranslatedError.mjs';
import Button from '../../components/atoms/Button.mjs';
import Column from '../../components/atoms/Column.mjs';
import { useCountdown } from '../../components/atoms/Countdown.mjs';
import ButtonColumn from '../../components/molecules/ButtonColumn.mjs';
import { LoadingScreen } from '../../components/molecules/Loading.mjs';
import { ResendOTPButton } from '../../components/organisms/ResendOTPButton.mjs';
import { SentOTPEntry } from '../../components/organisms/SentOTPEntry.mjs';
import { useStytch, useConfig, useGlobalReducer } from '../GlobalContextProvider.mjs';
import { useEmailOtpDiscoverySend } from '../hooks/useEmailOtpDiscoverySend.mjs';
import { useEmailOtpLoginOrSignup } from '../hooks/useEmailOtpLoginOrSignup.mjs';
import { useMutate, onDiscoveryAuthenticateSuccess, onAuthenticateSuccess } from '../utils.mjs';
import { AuthFlowType } from '../../../../../core/src/public/b2b/ui.mjs';

const EmailOTPEntryScreen = ()=>{
    const stytchClient = useStytch();
    const config = useConfig();
    const { i18n: $__i18n, _: $__ } = useLingui();
    const [state, dispatch] = useGlobalReducer();
    const { codeExpiration } = state.formState.otpState;
    const resendCountdown = useCountdown();
    const { userSuppliedEmail } = state.formState.emailState;
    const emailOtp = useEmailOtpLoginOrSignup({
        throwOnError: true
    });
    const emailOtpDiscovery = useEmailOtpDiscoverySend({
        throwOnError: true
    });
    const isSending = emailOtp.isMutating || emailOtpDiscovery.isMutating;
    const sendError = emailOtp.error || emailOtpDiscovery.error;
    const discoveryAuthenticate = useMutate('stytch.otps.email.discovery.authenticate', (_, { arg: { otp, email } })=>stytchClient.otps.email.discovery.authenticate({
            code: otp,
            email_address: email
        }), {
        onSuccess: (data)=>{
            onDiscoveryAuthenticateSuccess(data, dispatch);
        },
        throwOnError: true
    });
    const authenticate = useMutate('stytch.otps.email.authenticate', (_, { arg: { otp, emailAddress, organizationId, sessionDurationMinutes } })=>stytchClient.otps.email.authenticate({
            code: otp,
            email_address: emailAddress,
            organization_id: organizationId,
            session_duration_minutes: sessionDurationMinutes
        }), {
        onSuccess: (data)=>{
            onAuthenticateSuccess(data, dispatch, config);
        },
        throwOnError: true
    });
    const isAuthenticatingAny = discoveryAuthenticate.isMutating || authenticate.isMutating;
    const error = discoveryAuthenticate.error || authenticate.error || sendError;
    const errorMessage = error ? getTranslatedError(error, $__) : undefined;
    const resetAll = ()=>{
        for (const resp of [
            emailOtp,
            emailOtpDiscovery,
            authenticate,
            discoveryAuthenticate
        ]){
            resp.reset();
        }
    };
    const handleSubmit = async (otp)=>{
        resetAll();
        try {
            if (state.flowState.type === AuthFlowType.Discovery) {
                await discoveryAuthenticate.trigger({
                    otp,
                    email: userSuppliedEmail
                });
            } else if (state.flowState.type === AuthFlowType.Organization && state.flowState.organization && state.formState.emailState.userSuppliedEmail) {
                await authenticate.trigger({
                    otp,
                    emailAddress: state.formState.emailState.userSuppliedEmail,
                    organizationId: state.flowState.organization.organization_id,
                    sessionDurationMinutes: config.sessionOptions.sessionDurationMinutes
                });
            }
        } catch  {
            resendCountdown.clear();
        }
    };
    const handleResendOTP = async ()=>{
        resetAll();
        if (isSending) return;
        if (state.flowState.type === AuthFlowType.Discovery) {
            await emailOtpDiscovery.trigger({
                email: userSuppliedEmail
            });
        } else if (state.flowState.type === AuthFlowType.Organization && state.flowState.organization) {
            await emailOtp.trigger({
                email: userSuppliedEmail,
                organization_id: state.flowState.organization.organization_id
            });
        }
    };
    const handleBack = ()=>{
        dispatch({
            type: 'navigate_back'
        });
    };
    return /*#__PURE__*/ React__default.createElement(Column, {
        gap: 6
    }, codeExpiration !== null ? /*#__PURE__*/ React__default.createElement(SentOTPEntry, {
        isSubmitting: isAuthenticatingAny,
        onSubmit: handleSubmit,
        errorMessage: errorMessage,
        expiration: codeExpiration.getTime(),
        formattedDestination: userSuppliedEmail
    }) : /*#__PURE__*/ React__default.createElement(LoadingScreen, null), /*#__PURE__*/ React__default.createElement(ButtonColumn, null, /*#__PURE__*/ React__default.createElement(ResendOTPButton, {
        countdown: resendCountdown,
        resendOTP: handleResendOTP,
        isSubmitting: isAuthenticatingAny
    }), /*#__PURE__*/ React__default.createElement(Button, {
        variant: "ghost",
        onClick: handleBack
    }, $__i18n._({
        id: "button.goBack",
        message: "Go back"
    }))));
};

export { EmailOTPEntryScreen };
//# sourceMappingURL=EmailOTPEntryScreen.mjs.map
