import { useLingui } from '../../../../../../node_modules/@lingui/react/dist/index.mjs';
import React__default, { useMemo, useState, useEffect } from 'react';
import { debounce, noop } from '../../../utils/index.mjs';
import { clearStytchTokenParams } from '../../../utils/createAuthUrlHandler.mjs';
import { getTranslatedError } from '../../../utils/getTranslatedError.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 EmailInput from '../../components/molecules/EmailInput.mjs';
import { getNewPasswordProps, PasswordError } from '../../components/molecules/PasswordError.mjs';
import { PasswordInput } from '../../components/molecules/PasswordInput.mjs';
import { useStytch, useConfig, useGlobalReducer, useEventCallback, useErrorCallback } from '../GlobalContextProvider.mjs';
import { AppScreens } from '../types/AppScreens.mjs';
import { useBootstrap, onAuthenticateSuccess } from '../utils.mjs';
import { DEFAULT_SESSION_DURATION_MINUTES } from '../../../../../core/src/constants.mjs';
import { StytchEventType } from '../../../../../core/src/public/ui.mjs';

const PasswordResetForm = ()=>{
    const stytchClient = useStytch();
    const config = useConfig();
    const [, dispatch] = useGlobalReducer();
    const bootstrap = useBootstrap();
    const { i18n: $__i18n, _: $__ } = useLingui();
    const onEvent = useEventCallback();
    const onError = useErrorCallback();
    const [resetToken, resetTokenType] = useMemo(()=>{
        const parsed = stytchClient.parseAuthenticateUrl();
        if (!parsed) return [
            '',
            ''
        ];
        return [
            parsed.token,
            parsed.tokenType
        ];
    }, [
        stytchClient
    ]);
    const dataLayer = readB2BInternals(stytchClient).dataLayer;
    const email = dataLayer.getItem('reset-email-value');
    const [password, setPassword] = useState('');
    const [errorMessage, setErrorMessage] = useState('');
    const [passwordError, setPasswordError] = useState({
        policy: 'notLoaded'
    });
    const [isSubmitting, setIsSubmitting] = useState(false);
    const updateStrengthCheck = useMemo(()=>debounce((password)=>{
            setErrorMessage('');
            return stytchClient.passwords.strengthCheck({
                password
            }).then(({ score, valid_password, zxcvbn_feedback, luds_feedback, strength_policy, breached_password })=>{
                const common = {
                    passwordInvalid: !valid_password,
                    isPasswordBreached: breached_password
                };
                if (strength_policy === 'zxcvbn') {
                    setPasswordError({
                        policy: strength_policy,
                        ...common,
                        passwordScore: score,
                        passwordWarning: zxcvbn_feedback.warning,
                        passwordSuggestions: zxcvbn_feedback.suggestions
                    });
                } else if (strength_policy === 'luds') {
                    setPasswordError({
                        policy: strength_policy,
                        ...common,
                        missingCharacters: luds_feedback.missing_characters,
                        missingComplexity: luds_feedback.missing_complexity
                    });
                }
            }).catch((e)=>{
                setErrorMessage(getTranslatedError(e, $__));
            });
        }), [
        stytchClient.passwords,
        $__
    ]);
    useEffect(()=>{
        if (resetTokenType === 'multi_tenant_magic_links') {
            stytchClient.magicLinks.authenticate({
                magic_links_token: resetToken,
                session_duration_minutes: config.sessionOptions?.sessionDurationMinutes ?? DEFAULT_SESSION_DURATION_MINUTES,
                locale: config.emailMagicLinksOptions?.locale
            }).then((data)=>{
                clearStytchTokenParams();
                dispatch({
                    type: 'primary_authenticate_success',
                    response: data,
                    includedMfaMethods: config.mfaProductInclude,
                    resetTokenType
                });
            }).catch((e)=>{
                setErrorMessage(getTranslatedError(e, $__));
                onError(e);
            });
            return;
        }
    // eslint-disable-next-line react-hooks/exhaustive-deps -- SDK-1354
    }, [
        resetTokenType
    ]);
    const onPasswordChange = (password)=>{
        setPassword(password);
        updateStrengthCheck(password);
    };
    const handleSubmit = (e)=>{
        e.preventDefault();
        setErrorMessage('');
        setIsSubmitting(true);
        if (resetTokenType == 'multi_tenant_passwords') {
            stytchClient.passwords.resetByEmail({
                password_reset_token: resetToken,
                password,
                session_duration_minutes: config.sessionOptions?.sessionDurationMinutes ?? DEFAULT_SESSION_DURATION_MINUTES,
                locale: config.passwordOptions?.locale
            }).then((data)=>{
                setIsSubmitting(false);
                onEvent({
                    type: StytchEventType.B2BPasswordResetByEmail,
                    data
                });
                onAuthenticateSuccess(data, dispatch, config);
            }).catch((e)=>{
                onError(e);
                setErrorMessage(getTranslatedError(e, $__));
                setIsSubmitting(false);
            });
        } else if (resetTokenType == 'discovery') {
            stytchClient.passwords.discovery.resetByEmail({
                password_reset_token: resetToken,
                password
            }).then((data)=>{
                setIsSubmitting(false);
                onEvent({
                    type: StytchEventType.B2BDiscoveryPasswordReset,
                    data
                });
                dispatch({
                    type: 'set_discovery_state',
                    email: data.email_address,
                    discoveredOrganizations: data.discovered_organizations
                });
                dispatch({
                    type: 'transition',
                    screen: AppScreens.Discovery
                });
            }).catch((e)=>{
                onError(e);
                setErrorMessage(getTranslatedError(e, $__));
                setIsSubmitting(false);
            });
        } else {
            stytchClient.passwords.resetBySession({
                password
            }).then((data)=>{
                setIsSubmitting(false);
                onEvent({
                    type: StytchEventType.B2BPasswordResetBySession,
                    data
                });
                dispatch({
                    type: 'transition',
                    screen: AppScreens.LoggedIn
                });
            }).catch((e)=>{
                onError(e);
                setErrorMessage(getTranslatedError(e, $__));
                setIsSubmitting(false);
            });
        }
    };
    const passwordInputProps = getNewPasswordProps(bootstrap, passwordError.policy);
    return /*#__PURE__*/ React__default.createElement(Column, {
        gap: 6,
        as: "form",
        onSubmit: handleSubmit
    }, /*#__PURE__*/ React__default.createElement(Typography, {
        variant: "header"
    }, $__i18n._({
        id: "password.setNew.title",
        message: "Set a new password"
    })), /*#__PURE__*/ React__default.createElement(Column, {
        gap: 2
    }, email ? /*#__PURE__*/ React__default.createElement(EmailInput, {
        email: email,
        setEmail: noop,
        disabled: true
    }) : null, /*#__PURE__*/ React__default.createElement(PasswordInput, {
        password: password,
        setPassword: onPasswordChange,
        error: errorMessage,
        ...passwordInputProps
    }), /*#__PURE__*/ React__default.createElement(PasswordError, {
        bootstrap: bootstrap,
        ...passwordError
    }), /*#__PURE__*/ React__default.createElement(Button, {
        variant: "primary",
        loading: isSubmitting,
        type: "submit",
        disabled: passwordError.policy === 'notLoaded' || passwordError.passwordInvalid
    }, $__i18n._({
        id: "button.continue",
        message: "Continue"
    }))));
};

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