import { __rest } from "tslib";
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useState } from 'react';
import { styled } from '@mui/material/styles';
import { Box, Button, CircularProgress, FormGroup, IconButton, InputAdornment, Popover, Typography } from '@mui/material';
import classNames from 'classnames';
import { defineMessages, FormattedMessage, useIntl } from 'react-intl';
import { formatHttpErrorCode, UserService } from '@selfcommunity/api-services';
import { SCOPE_SC_UI } from '../../../constants/Errors';
import { Logger } from '@selfcommunity/utils';
import BaseDialog from '../../../shared/BaseDialog';
import PasswordTextField from '../../../shared/PasswordTextField';
import EmailTextField from '../../../shared/EmailTextField';
import { LoadingButton } from '@mui/lab';
import Icon from '@mui/material/Icon';
import { useSnackbar } from 'notistack';
import { PREFIX } from '../constants';
const messages = defineMessages({
    changePasswordTitle: {
        id: 'ui.userProfileEditAccountCredentials.changePassword',
        defaultMessage: 'ui.userProfileEditAccountCredentials.changePassword'
    },
    confirmPasswordError: {
        id: 'ui.userProfileEditAccountCredentials.confirmPassword.error',
        defaultMessage: 'ui.userProfileEditAccountCredentials.confirmPassword.error'
    }
});
const classes = {
    root: `${PREFIX}-account-credentials-root`,
    email: `${PREFIX}-email`,
    success: `${PREFIX}-success`,
    error: `${PREFIX}-error`,
    dialogRoot: `${PREFIX}-password-dialog-root`,
    form: `${PREFIX}-password-form`,
    formField: `${PREFIX}-form-field`,
    password: `${PREFIX}-password`,
    confirmChangeButton: `${PREFIX}-confirm-change-button`
};
const Root = styled(Box, {
    name: PREFIX,
    slot: 'AccountCredentialsRoot'
})(() => ({}));
const PasswordDialogRoot = styled(BaseDialog, {
    name: PREFIX,
    slot: 'PasswordDialogRoot'
})(() => ({}));
export default function AccountCredentials(props) {
    var _a;
    // PROPS
    const { className = null, user, skipEmailValidation = false } = props, rest = __rest(props, ["className", "user", "skipEmailValidation"]);
    const { enqueueSnackbar } = useSnackbar();
    // STATE
    const [openChangePasswordDialog, setOpenChangePasswordDialog] = useState(false);
    const initialFieldState = {
        email: (_a = user === null || user === void 0 ? void 0 : user.email) !== null && _a !== void 0 ? _a : '',
        password: '',
        newPassword: '',
        confirmPassword: ''
    };
    const initialErrorState = {
        email: '',
        password: '',
        newPassword: '',
        confirmPassword: ''
    };
    const [field, setField] = useState(initialFieldState);
    const [error, setError] = useState(initialErrorState);
    const [isEditing, setIsEditing] = useState(false);
    const [isSubmittingPassword, setIsSubmittingPassword] = useState(false);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [anchorEl, setAnchorEl] = useState(null);
    const open = Boolean(anchorEl);
    // INTL
    const intl = useIntl();
    // HANDLERS
    const handlePopoverOpen = (event) => {
        setAnchorEl(event.currentTarget);
    };
    const handlePopoverClose = () => {
        setAnchorEl(null);
    };
    const handleChange = (event) => {
        const { name, value } = event.target;
        setField((prev) => (Object.assign(Object.assign({}, prev), { [name]: value })));
        if (!value) {
            setError((prev) => (Object.assign(Object.assign({}, prev), { [name]: value })));
        }
        else {
            setError((prev) => (Object.assign(Object.assign({}, prev), { [name]: '' })));
        }
    };
    const handleEmailBlur = (e) => {
        if (!e.target.value) {
            setField((prev) => (Object.assign(Object.assign({}, prev), { ['email']: user === null || user === void 0 ? void 0 : user.email })));
            setIsEditing(false);
        }
    };
    const validateInput = () => {
        if (field.newPassword !== field.confirmPassword) {
            setError((prev) => (Object.assign(Object.assign({}, prev), { ['confirmPassword']: intl.formatMessage(messages.confirmPasswordError) })));
        }
    };
    const handleCloseDialog = () => {
        setOpenChangePasswordDialog(false);
        setField(initialFieldState);
        setError(initialErrorState);
    };
    const handleSubmitPassword = (event) => {
        event.preventDefault();
        event.stopPropagation();
        setIsSubmittingPassword(true);
        UserService.changeUserPassword(user === null || user === void 0 ? void 0 : user.id, field.password, field.newPassword)
            .then(() => {
            setIsSubmittingPassword(false);
            handleCloseDialog();
        })
            .catch((error) => {
            setIsSubmittingPassword(false);
            const _error = formatHttpErrorCode(error);
            Logger.error(SCOPE_SC_UI, error);
            if (_error.passwordError) {
                setError((prev) => (Object.assign(Object.assign({}, prev), { ['password']: _error.passwordError.error })));
            }
            if (_error.newPasswordError) {
                setError((prev) => (Object.assign(Object.assign({}, prev), { ['newPassword']: _error.newPasswordError.error })));
            }
        });
    };
    const handleSubmitEmail = (e) => {
        e.preventDefault();
        e.stopPropagation();
        setIsSubmitting(true);
        UserService.changeUserMail(user === null || user === void 0 ? void 0 : user.id, field.email, !skipEmailValidation, !skipEmailValidation)
            .then((res) => {
            setIsEditing(false);
            setIsSubmitting(false);
            if (skipEmailValidation) {
                enqueueSnackbar(_jsx(FormattedMessage, { id: "ui.userProfileEditAccountCredentials.email.success", defaultMessage: "ui.userProfileEditAccountCredentials.email.success" }), {
                    variant: 'success',
                    autoHideDuration: 3000
                });
            }
            else {
                enqueueSnackbar(_jsx(FormattedMessage, { id: "ui.userProfileEditAccountCredentials.email.successConfirm", defaultMessage: "ui.userProfileEditAccountCredentials.email.successConfirm" }), {
                    variant: 'warning',
                    autoHideDuration: 5000
                });
            }
        })
            .catch((error) => {
            setIsSubmitting(false);
            const _error = formatHttpErrorCode(error);
            setError((prev) => (Object.assign(Object.assign({}, prev), { ['email']: _error.newEmailError ? `newEmailError.${_error.newEmailError.error}` : _error.error })));
        });
    };
    if (!user) {
        return;
    }
    return (_jsxs(Root, Object.assign({ className: classNames(classes.root, className) }, rest, { children: [_jsxs(_Fragment, { children: [_jsx(Typography, Object.assign({ variant: "body1", className: classes.email }, { children: _jsx(FormattedMessage, { id: "ui.userProfileEditAccountCredentials.email", defaultMessage: "ui.userProfileEditAccountCredentials.email" }) })), _jsx(_Fragment, { children: isSubmitting ? (_jsx(CircularProgress, {})) : (_jsx(_Fragment, { children: _jsx(EmailTextField, { name: "email", disabled: !isEditing || isSubmitting, size: "small", value: field.email, onChange: handleChange, onBlur: handleEmailBlur, error: Boolean(error.email), helperText: error.email && (_jsx(FormattedMessage, { id: `ui.userProfileEditAccountCredentials.email.error.${error.email}`, defaultMessage: `ui.userProfileEditAccountCredentials.email.error.${error.email}` })), InputProps: {
                                    endAdornment: (_jsx(InputAdornment, Object.assign({ position: "end" }, { children: !isEditing ? (_jsx(IconButton, Object.assign({ onClick: () => setIsEditing(true), edge: "end" }, { children: _jsx(Icon, { children: "edit" }) }))) : error.email ? (_jsx(Icon, Object.assign({ color: "error" }, { children: "error" }))) : (_jsx(IconButton, Object.assign({ onClick: handleSubmitEmail, edge: "end", color: "primary", disabled: !field.email || error.email }, { children: _jsx(Icon, { children: "check" }) }))) })))
                                } }) })) }), _jsx(Typography, Object.assign({ variant: "body1", className: classes.password }, { children: _jsx(FormattedMessage, { id: "ui.userProfileEditAccountCredentials.passwordLabel", defaultMessage: "ui.userProfileEditAccountCredentials.passwordLabel" }) })), _jsx(Button, Object.assign({ size: "small", variant: "outlined", onClick: () => setOpenChangePasswordDialog(true), sx: { mb: 1 } }, { children: _jsx(FormattedMessage, { id: "ui.userProfileEditAccountCredentials.changePassword", defaultMessage: "ui.userProfileEditAccountCredentials.changePassword" }) }))] }), openChangePasswordDialog && (_jsxs(PasswordDialogRoot, Object.assign({ className: classes.dialogRoot, title: intl.formatMessage(messages.changePasswordTitle), open: openChangePasswordDialog, onClose: handleCloseDialog }, rest, { children: [_jsxs(FormGroup, Object.assign({ className: classes.form }, { children: [_jsx(PasswordTextField, { className: classes.formField, name: "password", disabled: isSubmittingPassword, label: _jsx(FormattedMessage, { id: "ui.userProfileEditAccountCredentials.password", defaultMessage: "ui.userProfileEditAccountCredentials.password" }), size: "medium", value: field.password, onChange: handleChange, error: Boolean(error.password), helperText: error.password && (_jsx(FormattedMessage, { id: `ui.userProfileEditAccountCredentials.password.error.${error.password}`, defaultMessage: `ui.userProfileEditAccountCredentials.password.error.${error.password}` })) }), _jsx(PasswordTextField, { name: "newPassword", className: classes.formField, disabled: isSubmittingPassword, label: _jsx(FormattedMessage, { id: "ui.userProfileEditAccountCredentials.newPassword", defaultMessage: "ui.userProfileEditAccountCredentials.newPassword" }), size: "medium", value: field.newPassword, onChange: handleChange, error: Boolean(error.newPassword), helperText: error.newPassword && (_jsx(FormattedMessage, { id: `ui.userProfileEditAccountCredentials.newPassword.error.${error.newPassword}`, defaultMessage: `ui.userProfileEditAccountCredentials.newPassword.error.${error.newPassword}` })), InputProps: {
                                    endAdornment: (_jsx(InputAdornment, Object.assign({ position: "end" }, { children: _jsx(IconButton, Object.assign({ "aria-label": "info", onClick: handlePopoverOpen, edge: "end" }, { children: _jsx(Icon, { children: "info" }) })) })))
                                } }), _jsx(Popover, Object.assign({ open: open, anchorEl: anchorEl, anchorOrigin: {
                                    vertical: 'center',
                                    horizontal: 'left'
                                }, transformOrigin: {
                                    vertical: 'center',
                                    horizontal: 'right'
                                }, onClose: handlePopoverClose }, { children: _jsx(Box, Object.assign({ sx: { p: '10px' } }, { children: _jsx(Typography, Object.assign({ component: 'span', sx: { whiteSpace: 'pre-line' } }, { children: _jsx(FormattedMessage, { id: "ui.userProfileEditAccountCredentials.newPassword.info", defaultMessage: "ui.userProfileEditAccountCredentials.newPassword.info" }) })) })) })), _jsx(PasswordTextField, { name: "confirmPassword", className: classes.formField, disabled: isSubmittingPassword, label: _jsx(FormattedMessage, { id: "ui.userProfileEditAccountCredentials.confirmPassword", defaultMessage: "ui.userProfileEditAccountCredentials.confirmPassword" }), size: "medium", value: field.confirmPassword, onChange: handleChange, onBlur: validateInput, error: Boolean(error.confirmPassword), helperText: error.confirmPassword })] })), _jsx(LoadingButton, Object.assign({ className: classes.confirmChangeButton, loading: isSubmittingPassword, disabled: !field.confirmPassword || Boolean(error.confirmPassword) || Boolean(error.password) || Boolean(error.newPassword), variant: "contained", onClick: handleSubmitPassword }, { children: _jsx(FormattedMessage, { id: "ui.userProfileEditAccountCredentials.changePassword", defaultMessage: "ui.userProfileEditAccountCredentials.changePassword" }) }))] })))] })));
}
