import PropTypes from 'prop-types';
import React, { Component } from 'react';
import get from 'lodash/get';
import { EMPLOYEEGROUP_FIELD_CONFIG_CHOICES } from '../../constants/config';
const { HIDDEN, REQUIRED } = EMPLOYEEGROUP_FIELD_CONFIG_CHOICES;
import injectSheet from 'react-jss';
import classnames from 'classnames';

import styles from './styles/FormComponent';

export  class FormComponent extends Component {
    constructor(){
        super();
        this.onChange = this.onChange.bind(this);
    }

    onChange(val){
        const { onChange, name } = this.props;
        onChange(name, val);
    }

    render(){
        const { FieldComponent, fieldConfig, formData, formErrors, name, classes, className, showLabel, isAlwaysRequired, showValidationErrors, hideValue } = this.props;
        const value = get(formData, name);
        const fieldConfigName = this.props.fieldConfigName || name;
        let label = this.props.label;
        if (fieldConfig[fieldConfigName] === REQUIRED || isAlwaysRequired) {
            label = `${this.props.label} *`;
        }

        const error = showValidationErrors && get(formErrors, name);

        if (fieldConfig[fieldConfigName] === HIDDEN) {
            return null;
        }

        return (
            <div className={classnames(classes.formComponent, {
                [className]: className,
                'has-error': !!error
            })}>
                {
                    showLabel &&
                    <label className={classes.label} htmlFor={name}>{ label }</label>
                }
                <FieldComponent {...this.props} onChange={this.onChange} value={hideValue ? '' : value} />
                {
                    error &&
                    <div className={classes.errorText}>{ error }</div>
                }
            </div>
        );
    }
}

FormComponent.defaultProps = {
    showLabel: true
};

FormComponent.propTypes = {
    classes: PropTypes.object.isRequired,
    className: PropTypes.string,
    label: PropTypes.string,
    onChange: PropTypes.func.isRequired,
    FieldComponent: PropTypes.func.isRequired,
    isAlwaysRequired: PropTypes.bool,
    name: PropTypes.string.isRequired,
    formErrors: PropTypes.object.isRequired,
    formData: PropTypes.object.isRequired,
    fieldConfig: PropTypes.object.isRequired,
    fieldConfigName: PropTypes.string,
    showLabel: PropTypes.bool.isRequired,
    showValidationErrors: PropTypes.bool,
    hideValue: PropTypes.bool,
};

export default injectSheet(styles)(FormComponent);

