import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import Icon from '../Icon';
import Translate from '../Translate';
import './styles.scss';

class InputCheckbox extends Component {
    constructor(props) {
        super(props);

        this.state = {
            hasError: this.props.hasError,
            isChecked: this.props.isChecked,
            isDisabled: this.props.isDisabled,
        };

        this.handleInputChange = this.handleInputChange.bind(this);
    }

    componentWillReceiveProps(props) {
        this.setState({
            ...props,
        });
    }

    handleInputChange() {
        this.setState({
            isChecked: !this.state.isChecked,
        }, () => {
            this.props.onChange(this.state.isChecked);
        });
    }

    render() {
        const classNames = classnames('Checkbox', {
            Checkbox_error: this.state.hasError,
        });

        return (
            <label
                htmlFor={this.props.elementId}
                className={classNames}
            >
                <input
                    id={this.props.elementId}
                    className="Checkbox__input"
                    onChange={this.handleInputChange}
                    disabled={this.state.isDisabled}
                    checked={this.state.isChecked}
                    type="checkbox"
                />
                <span className="Checkbox__label">
                    <Translate tag={this.props.label} />
                    <span className="Checkbox__label-icon">
                        <Icon
                            name="check"
                            size="extra-small"
                            color="white"
                        />
                    </span>
                </span>
                {this.props.description ? (
                    <div className="Checkbox__description">
                        <Translate tag={this.props.description} />
                    </div>
                ) : null}
            </label>
        );
    }
}

InputCheckbox.propTypes = {
    elementId: PropTypes.string.isRequired,
    label: PropTypes.string,
    description: PropTypes.string,
    isDisabled: PropTypes.bool,
    isChecked: PropTypes.bool,
    hasError: PropTypes.bool,
    onChange: PropTypes.func,
};

InputCheckbox.defaultProps = {
    label: '',
    description: '',
    isDisabled: false,
    isChecked: false,
    hasError: false,
    onChange: () => {},
};

export default InputCheckbox;
