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

class Switch extends Component {
    constructor(props) {
        super(props);
        this.state = {
            model: props.model,
        };
        this.handleToggleCheckbox = this.handleToggleCheckbox.bind(this);
    }

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

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

    render() {
        const className = `Switch ${this.props.commonStyle}`;
        const switchControlClassName = `Switch__control ${this.props.activeStyle}`;

        return (
            <div className={className}>
                <div className="Switch__label">
                    {this.props.label}
                </div>
                <div className={switchControlClassName}>
                    <input
                        type="checkbox"
                        checked={this.state.model}
                        onChange={this.handleToggleCheckbox}
                        id={this.props.elementId}
                    />
                    <label
                        htmlFor={this.props.elementId}
                        role="presentation"
                    />
                </div>
            </div>
        );
    }
}

Switch.propTypes = {
    model: PropTypes.bool.isRequired,
    label: PropTypes.string,
    commonStyle: PropTypes.string,
    activeStyle: PropTypes.string,
    elementId: PropTypes.string,
    onChange: PropTypes.func.isRequired,
};

Switch.defaultProps = {
    label: '',
    commonStyle: '',
    activeStyle: '',
    elementId: '',
};

export default Switch;
