import { useLingui } from '../../../../../../../node_modules/@lingui/react/dist/index.mjs';
import React__default, { useState, useEffect } from 'react';
import { getTranslatedError } from '../../../../utils/getTranslatedError.mjs';
import { formatNumber } from '../../../../utils/handleParsePhoneNumber.mjs';
import { readB2CInternals } from '../../../../utils/internal.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 { ResendOTPButton } from '../../../components/organisms/ResendOTPButton.mjs';
import { SentOTPEntry } from '../../../components/organisms/SentOTPEntry.mjs';
import { useEventCallback, useErrorCallback, useStytch, useConfig, useGlobalReducer, AppScreens } from '../../GlobalContextProvider.mjs';
import { OTPMethods, StytchEventType } from '../../../../../../core/src/public/ui.mjs';
import { DEFAULT_OTP_EXPIRATION_MINUTES, DEFAULT_SESSION_DURATION_MINUTES } from '../../../../../../core/src/constants.mjs';
import { EmailSentType } from '../../../../../../core/src/Events.mjs';

const OTPAuthenticate = ({ hideBackButton = false })=>{
    const { i18n: $__i18n, _: $__ } = useLingui();
    const onEvent = useEventCallback();
    const onError = useErrorCallback();
    const stytchClient = useStytch();
    const config = useConfig();
    const [state, dispatch] = useGlobalReducer();
    const [isSubmitting, setIsSubmitting] = useState(false);
    const destination = state.formState.otpState.otpDestination;
    const selectionMethod = state.formState.otpState.type;
    const [errorMessage, setErrorMessage] = useState('');
    const [formattedDestination, setFormattedDestination] = useState(destination);
    const calculateExpiration = ()=>Date.now() + 1000 * 60 * (config.otpOptions?.expirationMinutes ?? DEFAULT_OTP_EXPIRATION_MINUTES);
    useEffect(()=>{
        const parseDestination = async ()=>{
            const parsePhoneNumber = (phoneNumber)=>readB2CInternals(stytchClient).clientsideServices.parsedPhoneNumber({
                    phoneNumber
                });
            const national = await formatNumber({
                parsePhoneNumber,
                phoneNumber: destination
            });
            setFormattedDestination(selectionMethod === OTPMethods.Email ? destination : national);
        };
        parseDestination();
    }, [
        selectionMethod,
        destination,
        stytchClient
    ]);
    const [expiration, setExpiration] = useState(calculateExpiration);
    const resendCountdown = useCountdown();
    const resendOTP = async ()=>{
        if (selectionMethod === OTPMethods.Email) {
            readB2CInternals(stytchClient).networkClient.logEvent({
                name: 'email_try_again_clicked',
                details: {
                    email: destination,
                    type: EmailSentType.LoginOrCreateOTP
                }
            });
        }
        try {
            const data = await stytchClient.otps[selectionMethod].loginOrCreate(destination, {
                expiration_minutes: config.otpOptions?.expirationMinutes ?? DEFAULT_OTP_EXPIRATION_MINUTES
            });
            onEvent({
                type: StytchEventType.OTPsLoginOrCreateEvent,
                data
            });
            setExpiration(calculateExpiration());
            dispatch({
                type: 'update_otp_state',
                otpState: {
                    type: selectionMethod,
                    methodId: data.method_id,
                    otpDestination: destination
                }
            });
        } catch (e) {
            onError(e);
            setErrorMessage(getTranslatedError(e, $__));
            throw e;
        }
    };
    const handleSubmit = async (otp)=>{
        setIsSubmitting(true);
        stytchClient.otps.authenticate(otp, state.formState.otpState.methodId, {
            session_duration_minutes: config.sessionOptions?.sessionDurationMinutes ?? DEFAULT_SESSION_DURATION_MINUTES
        }).then((data)=>{
            onEvent({
                type: StytchEventType.OTPsAuthenticate,
                data
            });
            setIsSubmitting(false);
            dispatch({
                type: 'transition',
                screen: AppScreens.OTPConfirmation
            });
        }).catch((e)=>{
            onError(e);
            resendCountdown.clear();
            setIsSubmitting(false);
            setErrorMessage(getTranslatedError(e, $__));
        });
    };
    return /*#__PURE__*/ React__default.createElement(Column, {
        gap: 6
    }, /*#__PURE__*/ React__default.createElement(SentOTPEntry, {
        expiration: expiration,
        formattedDestination: formattedDestination,
        isSubmitting: isSubmitting,
        onSubmit: handleSubmit,
        errorMessage: errorMessage
    }), /*#__PURE__*/ React__default.createElement(ButtonColumn, null, /*#__PURE__*/ React__default.createElement(ResendOTPButton, {
        countdown: resendCountdown,
        resendOTP: resendOTP,
        isSubmitting: isSubmitting
    }), !hideBackButton && /*#__PURE__*/ React__default.createElement(Button, {
        variant: "ghost",
        onClick: ()=>dispatch({
                type: 'transition',
                screen: AppScreens.Main
            })
    }, $__i18n._({
        id: "button.goBack",
        message: "Go back"
    }))));
};

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