import { useLingui } from '../../../../../../node_modules/@lingui/react/dist/index.mjs';
import React__default from 'react';
import { getTranslatedError } from '../../../utils/getTranslatedError.mjs';
import { formatNumberToIncludeCountryCode } from '../../../utils/handleParsePhoneNumber.mjs';
import { readB2BInternals } from '../../../utils/internal.mjs';
import Button from '../../components/atoms/Button.mjs';
import Column from '../../components/atoms/Column.mjs';
import Typography from '../../components/atoms/Typography.mjs';
import ButtonColumn from '../../components/molecules/ButtonColumn.mjs';
import PhoneInput, { getPhoneNumberProps } from '../../components/molecules/PhoneInput.mjs';
import { useStytch, useGlobalReducer, useConfig } from '../GlobalContextProvider.mjs';
import { canGoBack } from '../reducer/navigation.mjs';
import { useMutate } from '../utils.mjs';
import { StytchSDKError } from '../../../../../core/src/public/SDKErrors.mjs';
import { COUNTRIES_LIST } from '../../../../../core/src/utils/country.mjs';

// eslint-disable-next-line lingui/no-unlocalized-strings
const DEFAULT_COUNTRY_CODE = 'US';
/**
 * Thrown when the user provides a phone number that cannot be parsed.
 */ class InvalidPhoneNumberError extends StytchSDKError {
    constructor(){
        // eslint-disable-next-line lingui/no-unlocalized-strings
        super('InvalidPhoneNumberError', 'Invalid phone number');
    }
}
const SMSOTPEnrollScreen = ()=>{
    const stytchClient = useStytch();
    const [state, dispatch] = useGlobalReducer();
    const { i18n: $__i18n, _: $__ } = useLingui();
    const { smsOtpOptions } = useConfig();
    const { mfa: { smsOtp: { isSending, sendError, enrolledNumber } } } = state;
    // This screen should only be shown if primary info is available
    const { memberId, organizationId } = state.mfa.primaryInfo;
    const [countryCode, setCountryCode] = React__default.useState(enrolledNumber?.countryCode ?? DEFAULT_COUNTRY_CODE);
    const [phoneNumber, setPhoneNumber] = React__default.useState(enrolledNumber?.phoneNumber ?? '');
    const errorMessage = React__default.useMemo(()=>{
        if (!sendError) return undefined;
        if (sendError instanceof InvalidPhoneNumberError) {
            return $__i18n._({
                id: "error.invalidPhoneNumber",
                message: "Phone number format is invalid. Ensure the phone number is in the E.164 format."
            });
        }
        return getTranslatedError(sendError, $__);
    }, [
        sendError,
        $__
    ]);
    const { parsePhoneNumber, getExampleNumber } = getPhoneNumberProps(readB2BInternals(stytchClient).clientsideServices);
    const { trigger: sendSms } = useMutate('stytch.otps.sms.send', async (_, { arg: { parsedNumber, locale } })=>{
        return stytchClient.otps.sms.send({
            mfa_phone_number: parsedNumber,
            member_id: memberId,
            organization_id: organizationId,
            locale: locale
        });
    }, {
        onSuccess: (response)=>{
            dispatch({
                type: 'sms_otp/send_success',
                response,
                countryCode,
                phoneNumber,
                formattedPhoneNumber: `+${COUNTRIES_LIST[countryCode]} ${phoneNumber}`
            });
        },
        onError: (error)=>{
            dispatch({
                type: 'sms_otp/send_error',
                error
            });
        }
    });
    const handleSubmit = async (e)=>{
        e.preventDefault();
        dispatch({
            type: 'sms_otp/send'
        });
        try {
            // We parse the phone number here (rather than inside `sendSms`) because we
            // don't want validation errors to be surfaced through the global error
            // callback
            const parsedNumber = await formatNumberToIncludeCountryCode({
                parsePhoneNumber,
                phoneNumber,
                country: countryCode
            });
            if (!parsedNumber.isValid) {
                throw new InvalidPhoneNumberError();
            }
            await sendSms({
                parsedNumber: parsedNumber.number,
                locale: smsOtpOptions?.locale
            });
        } catch (error) {
            dispatch({
                type: 'sms_otp/send_error',
                error
            });
        }
    };
    return /*#__PURE__*/ React__default.createElement(Column, {
        as: "form",
        gap: 6,
        onSubmit: handleSubmit
    }, /*#__PURE__*/ React__default.createElement(Typography, {
        variant: "header"
    }, $__i18n._({
        id: "mfa.smsEnrollment.title",
        message: "Enter your phone number to set up Multi-Factor Authentication"
    })), /*#__PURE__*/ React__default.createElement(Typography, {
        variant: "body"
    }, $__i18n._({
        id: "mfa.smsEnrollment.content",
        message: "Your organization requires an additional form of verification to make your account more secure."
    })), /*#__PURE__*/ React__default.createElement(PhoneInput, {
        country: countryCode,
        setCountry: setCountryCode,
        phone: phoneNumber,
        setPhone: setPhoneNumber,
        parsePhoneNumber: parsePhoneNumber,
        getExampleNumber: getExampleNumber,
        error: errorMessage
    }), /*#__PURE__*/ React__default.createElement(ButtonColumn, null, /*#__PURE__*/ React__default.createElement(Button, {
        variant: "primary",
        loading: isSending,
        type: "submit",
        disabled: !phoneNumber || isSending
    }, $__i18n._({
        id: "button.continue",
        message: "Continue"
    })), canGoBack(state) && /*#__PURE__*/ React__default.createElement(Button, {
        variant: "ghost",
        onClick: ()=>dispatch({
                type: 'navigate_back'
            })
    }, $__i18n._({
        id: "button.goBack",
        message: "Go back"
    }))));
};

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