import { FormControlLabel, FormLabel, IconButton, InputAdornment, makeStyles, } from '@material-ui/core';
import { Visibility, VisibilityOff } from '@material-ui/icons';
import React, { useCallback, useMemo, useState } from 'react';
import { Field } from '../../../../utilities/form/Field';
import PasswordValidator, { isPasswordValid } from '../PasswordValidator';
import { UserRoleAutoComplete } from './UserRoleAutoComplete';
import { FluentCheckbox } from '../../../../UI/inputs/checkbox';
import { FluentRadio, FluentRadioGroup } from '../../../../UI/inputs/radio';
import { FluentTextField } from '../../../../UI/inputs/textField';
import { useUser } from '../../../../utilities/auth';
import { useTranslation } from 'react-i18next';
const useStyles = makeStyles(theme => ({
    field: {
        marginBottom: theme.spacing(2),
    },
    selectors: {
        display: 'flex',
        flexDirection: 'row',
        marginBottom: theme.spacing(1),
    },
    alert: {
        marginTop: theme.spacing(-2),
        marginBottom: theme.spacing(2),
    },
    accountDisabledCheckbox: {
        height: 'auto',
    },
    accountDisabledCheckboxLabel: {
        marginTop: theme.spacing(1),
    },
}));
export const UserFormFields = props => {
    const { creationMethod, editedUser, handlePasswordTypeChange, handleCreationMethodChange, hideEmailField, passwordType, rolesData, showRolesField = true, altFieldMapping, } = props;
    const classes = useStyles();
    const user = useUser();
    const [showPassword, setShowPassword] = useState(false);
    const { t } = useTranslation();
    const userMapping = useMemo(() => {
        if (altFieldMapping) {
            return altFieldMapping;
        }
        else {
            // Default mapping for code generated User object
            return {
                userId: 'userId',
                firstName: 'firstName',
                lastName: 'lastName',
                email: 'email',
                roles: 'systemWideSecurityRoles',
            };
        }
    }, [altFieldMapping]);
    const roles = useMemo(() => {
        if (!rolesData) {
            return [];
        }
        rolesData.forEach(r => {
            r.label = r.name;
            r.value = r.name;
        });
        return rolesData
            .sort((a, b) => a.label.localeCompare(b.label))
            .sort((a, b) => a.productName.localeCompare(b.productName));
    }, [rolesData]);
    const initialRolesValue = useMemo(() => {
        if (!editedUser) {
            return [];
        }
        return roles.filter(r => {
            var _a;
            return !!((_a = editedUser[userMapping.roles]) === null || _a === void 0 ? void 0 : _a.find(edur => edur.roleId === r.roleId));
        });
    }, [editedUser, roles, userMapping]);
    const handleClickShowPassword = useCallback(() => {
        setShowPassword(!showPassword);
    }, [showPassword]);
    return (React.createElement(React.Fragment, null, editedUser && (React.createElement(Field, { component: FluentTextField, label: "User ID", id: "user-id", name: userMapping.userId, fullWidth: true, variant: "outlined", margin: "normal", size: "small", initialValue: editedUser === null || editedUser === void 0 ? void 0 : editedUser[userMapping.userId], disabled: true })), !editedUser && (React.createElement(React.Fragment, null, React.createElement(FormLabel, { component: "legend" }, t('Creation Method')), React.createElement(FluentRadioGroup, { "aria-labelledby": "creation-method", name: "creation-method", value: creationMethod, onChange: handleCreationMethodChange }, React.createElement(FormControlLabel, { value: "standard", control: React.createElement(FluentRadio, null), label: t('Standard (Email & Password)') }), React.createElement(FormControlLabel, { value: "invite", control: React.createElement(FluentRadio, null), label: t('Invite Entra User (Secure Email Invite Link)') })))), React.createElement(Field, { component: FluentTextField, label: "First Name", id: "first-name", name: userMapping.firstName, fullWidth: true, variant: "outlined", margin: "normal", size: "small", required: true, initialValue: editedUser === null || editedUser === void 0 ? void 0 : editedUser[userMapping.firstName], disabled: !user.can.CAN_MANAGE_USERS }), React.createElement(Field, { component: FluentTextField, label: "Last Name", id: "last-name", name: userMapping.lastName, fullWidth: true, variant: "outlined", margin: "normal", size: "small", required: true, initialValue: editedUser === null || editedUser === void 0 ? void 0 : editedUser[userMapping.lastName], disabled: !user.can.CAN_MANAGE_USERS }), !hideEmailField && (React.createElement(Field, { component: FluentTextField, label: "Email", id: "email", name: userMapping.email, fullWidth: true, variant: "outlined", margin: "normal", size: "small", required: true, initialValue: editedUser === null || editedUser === void 0 ? void 0 : editedUser[userMapping.email], disabled: editedUser && !user.can.CAN_MODIFY_EMAIL, validate: value => {
            if (!/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(value) ||
                64 < value.split('@')[0].length) {
                return 'Invalid email address';
            }
        } })), showRolesField && (React.createElement(Field, { component: UserRoleAutoComplete, ComponentProps: {
            initialValue: initialRolesValue,
            isFormField: true,
        }, label: "Select Role", id: "roles", name: userMapping.roles, fullWidth: true, variant: "outlined", margin: "normal", size: "small", options: roles || [], initialValue: initialRolesValue, textFieldProps: {
            id: 'roles',
            name: 'roles',
        }, optionLabel: 'label', groupBy: 'productName', required: true })), !editedUser && (creationMethod !== 'invite') && (React.createElement(React.Fragment, null, React.createElement(FluentRadioGroup, { "aria-labelledby": "password-type", name: "password-type", value: passwordType, onChange: handlePasswordTypeChange }, React.createElement(FormControlLabel, { value: "autoGeneratePassword", control: React.createElement(FluentRadio, null), label: "Auto-generate password" }), React.createElement(FormControlLabel, { value: "createPassword", control: React.createElement(FluentRadio, null), label: "Let me create the password" })), passwordType === 'createPassword' && (React.createElement(Field, { component: FluentTextField, label: "Password", id: "passwordProfile", name: "passwordProfile", type: showPassword ? 'text' : 'password', fullWidth: true, variant: "outlined", margin: "normal", size: "small", autoComplete: "new-password", validate: value => !isPasswordValid(value, 8, true, true, true, true) && (React.createElement(PasswordValidator, { password: value, numberRestriction: true, lowerCaseRestriction: true, upperCaseRestriction: true, lengthRestriction: 8, specialCharacterRestriction: true })), InputProps: {
            // <-- This is where the toggle button is added.
            endAdornment: (React.createElement(InputAdornment, { position: "end" }, React.createElement(IconButton, { "aria-label": "toggle password visibility", onClick: handleClickShowPassword }, showPassword ? React.createElement(Visibility, null) : React.createElement(VisibilityOff, null)))),
        } })), React.createElement(FormControlLabel, { className: classes.accountDisabledCheckboxLabel, label: 'Do not activate account and do not send a welcome email.', control: React.createElement(Field, { component: FluentCheckbox, id: "account-locked", name: "locked", type: "checkbox", disabled: !user.can.CAN_MANAGE_USERS, classes: classes }) })))));
};
//# sourceMappingURL=UserFormFields.js.map