import { useLingui } from '../../../../../../../node_modules/@lingui/react/dist/index.mjs';
import React__default, { useMemo, useState, useEffect } from 'react';
import { debounce } from '../../../../utils/index.mjs';
import { getTranslatedError } from '../../../../utils/getTranslatedError.mjs';
import Button from '../../../components/atoms/Button.mjs';
import Column from '../../../components/atoms/Column.mjs';
import Typography from '../../../components/atoms/Typography.mjs';
import VerticalTransition from '../../../components/atoms/VerticalTransition.mjs';
import ButtonColumn from '../../../components/molecules/ButtonColumn.mjs';
import ErrorText from '../../../components/molecules/ErrorText.mjs';
import { getNewPasswordProps, PasswordError } from '../../../components/molecules/PasswordError.mjs';
import { PasswordInput } from '../../../components/molecules/PasswordInput.mjs';
import { useStytch, useConfig, useGlobalReducer, useEventCallback, useErrorCallback, AppScreens } from '../../GlobalContextProvider.mjs';
import { useBootstrap } from '../../utils.mjs';
import { DEFAULT_SESSION_DURATION_MINUTES } from '../../../../../../core/src/constants.mjs';
import { StytchEventType } from '../../../../../../core/src/public/ui.mjs';

const ResetPasswordScreen = ()=>{
    const { i18n: $__i18n, _: $__ } = useLingui();
    const stytchClient = useStytch();
    const config = useConfig();
    const { bootstrap } = useBootstrap();
    const [state, dispatch] = useGlobalReducer();
    const passwordToken = state.formState.resetPasswordState.token;
    const onEvent = useEventCallback();
    const onError = useErrorCallback();
    const resetTokenType = useMemo(()=>{
        const parsed = stytchClient.parseAuthenticateUrl();
        return parsed?.tokenType ?? '';
    }, [
        stytchClient
    ]);
    const [password, setPassword] = useState('');
    const [passwordError, setPasswordError] = useState({
        policy: 'notLoaded'
    });
    const [errorMessage, setErrorMessage] = useState('');
    const [isSubmitting, setIsSubmitting] = useState(false);
    // Passwordless login states
    const [loginErrorMessage, setLoginErrorMessage] = useState('');
    const [isLoggingIn, setIsLoggingIn] = useState(false);
    const updateStrengthCheck = useMemo(()=>debounce((password)=>{
            setErrorMessage('');
            return stytchClient.passwords.strengthCheck({
                password
            }).then(({ score, feedback, valid_password, strength_policy, breached_password })=>{
                const common = {
                    passwordInvalid: !valid_password,
                    isPasswordBreached: breached_password
                };
                if (strength_policy === 'zxcvbn') {
                    setPasswordError({
                        policy: strength_policy,
                        ...common,
                        passwordScore: score,
                        passwordWarning: feedback.warning,
                        passwordSuggestions: feedback.suggestions
                    });
                } else if (strength_policy === 'luds') {
                    setPasswordError({
                        policy: strength_policy,
                        ...common,
                        missingCharacters: feedback.luds_requirements.missing_characters,
                        missingComplexity: feedback.luds_requirements.missing_complexity
                    });
                }
            });
        }), [
        stytchClient.passwords
    ]);
    useEffect(()=>{
        if (resetTokenType === 'login') {
            stytchClient.magicLinks.authenticate(passwordToken, {
                session_duration_minutes: config.sessionOptions?.sessionDurationMinutes ?? DEFAULT_SESSION_DURATION_MINUTES
            }).then(()=>{
                dispatch({
                    type: 'transition',
                    screen: AppScreens.PasswordConfirmation
                });
            }).catch((e)=>{
                onError(e);
            });
        }
    // 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);
        stytchClient.passwords.resetByEmail({
            token: passwordToken,
            password,
            session_duration_minutes: config.sessionOptions?.sessionDurationMinutes ?? DEFAULT_SESSION_DURATION_MINUTES
        }).then((data)=>{
            setIsSubmitting(false);
            onEvent({
                type: StytchEventType.PasswordResetByEmail,
                data
            });
            dispatch({
                type: 'transition',
                screen: AppScreens.PasswordConfirmation
            });
        }).catch((e)=>{
            onError(e);
            setErrorMessage(getTranslatedError(e, $__));
            setIsSubmitting(false);
        });
    };
    const handlePasswordlessLogin = ()=>{
        setLoginErrorMessage('');
        setIsLoggingIn(true);
        stytchClient.magicLinks.authenticate(passwordToken, {
            session_duration_minutes: config.sessionOptions?.sessionDurationMinutes ?? DEFAULT_SESSION_DURATION_MINUTES
        }).then(()=>{
            dispatch({
                type: 'transition',
                screen: AppScreens.PasswordConfirmation
            });
        }).catch((e)=>{
            onError(e);
            setLoginErrorMessage(getTranslatedError(e, $__));
        }).finally(()=>{
            setIsLoggingIn(false);
        });
    };
    if (resetTokenType === 'login') {
        return(// Same as <LoggingInScreen>, but use its own string ID
        /*#__PURE__*/ React__default.createElement(Typography, {
            variant: "header",
            align: "center"
        }, $__i18n._({
            id: "password.reset.loggingInProgress",
            message: "Logging in..."
        })));
    }
    const passwordInputProps = getNewPasswordProps(bootstrap, passwordError.policy);
    return /*#__PURE__*/ React__default.createElement("form", {
        onSubmit: handleSubmit
    }, /*#__PURE__*/ React__default.createElement(Column, {
        gap: 6
    }, /*#__PURE__*/ React__default.createElement(Typography, {
        variant: "header"
    }, $__i18n._({
        id: "password.reset.title",
        message: "Reset your password"
    })), /*#__PURE__*/ React__default.createElement(Column, {
        gap: 2
    }, /*#__PURE__*/ React__default.createElement(PasswordInput, {
        password: password,
        setPassword: onPasswordChange,
        error: errorMessage,
        ...passwordInputProps
    }), /*#__PURE__*/ React__default.createElement("div", null, errorMessage && /*#__PURE__*/ React__default.createElement(ErrorText, null, errorMessage), /*#__PURE__*/ React__default.createElement(PasswordError, {
        bootstrap: bootstrap,
        ...passwordError
    }))), /*#__PURE__*/ React__default.createElement(ButtonColumn, {
        top: /*#__PURE__*/ React__default.createElement(Button, {
            variant: "primary",
            loading: isSubmitting,
            type: "submit",
            disabled: passwordError.policy === 'notLoaded' || passwordError.passwordInvalid
        }, $__i18n._({
            id: "button.continue",
            message: "Continue"
        })),
        bottom: /*#__PURE__*/ React__default.createElement(Column, {
            gap: 2
        }, /*#__PURE__*/ React__default.createElement(Button, {
            variant: "outline",
            disabled: isLoggingIn,
            onClick: handlePasswordlessLogin,
            loading: isLoggingIn
        }, /*#__PURE__*/ React__default.createElement(VerticalTransition, {
            primary: $__i18n._({
                id: "password.reset.loginWithoutPassword",
                message: "Login without a password"
            }),
            secondary: $__i18n._({
                id: "login.loading",
                message: "Logging in..."
            }),
            triggered: isLoggingIn
        })), loginErrorMessage && /*#__PURE__*/ React__default.createElement(ErrorText, null, loginErrorMessage))
    })));
};

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