import PropTypes from 'prop-types';
import React from 'react';
import { Checkbox } from 'lego-on-react';
import { Permissions } from 'constants/Common';
import { i18n } from 'lib/i18n';
import PermissionStore from 'stores/Permissions';

import Form from 'ui/Form';
import Input from 'ui/Input';

function isDisabled() {
    return !PermissionStore.contains(Permissions.CHANGE_USER_PASSWORD);
}

const Password = React.createClass({
    getInitialState() {
        return {
            checked: true,
        };
    },

    _onChange(e) {
        this.setState({ checked: e.target.checked });
    },

    render() {
        const { changeRequiredFlag, errors } = this.props;
        const { checked } = this.state;
        const component = {};
        const disabled = isDisabled();

        if (changeRequiredFlag) {
            component.changeRequiredFlag = (
                <Form.Item key="changeRequiredFlag">
                    <Checkbox
                        size="m"
                        theme="normal"
                        name={Form.getSafeFieldName('password_change_required')}
                        text={i18n('user.change_password_on_next_visit')}
                        onChange={this._onChange}
                        checked={checked}
                        disabled={disabled}
                    />
                </Form.Item>
            );
        }

        return (
            <div className="form__subsection">
                <Form.Item
                    key="password"
                    label={i18n('user.password')}
                    errors={errors.password}
                    required
                >
                    <Input
                        name={Form.getSafeFieldName('password')}
                        type="password"
                        hasClear
                        size="m"
                        autoComplete={false}
                        disabled={disabled}
                        width="available"
                    />
                </Form.Item>
                <Form.Item
                    key="password_confirmation"
                    label={i18n('user.password_confirmation')}
                    errors={errors.passwordConfirmation}
                    required
                >
                    <Input
                        name={Form.getSafeFieldName('password_confirmation')}
                        type="password"
                        hasClear
                        size="m"
                        autoComplete={false}
                        disabled={disabled}
                        width="available"
                    />
                </Form.Item>
                {component.changeRequiredFlag}
            </div>
        );
    },
});

Password.propTypes = {
    errors: PropTypes.object,
    changeRequiredFlag: PropTypes.bool,
};

Password.defaultProps = {
    changeRequiredFlag: false,
    errors: {},
};

export default Password;
