import * as React from 'react';
// import {isEmpty} from 'lodash';
import classNames from 'classnames';
import {getId} from '../function';
import RenderHtml from '../renderFunction';
import PropsTypes from './types';
import FormComponent from '../FormComponent';

interface State extends PropsTypes {
    uuid: string,
    doValidate: boolean
}

export default class Button extends FormComponent<PropsTypes, State> {

    public state: State;

    // private input = React.createRef<HTMLInputElement>();

    constructor(props: PropsTypes, {}) {
        super(props);
        const uuid = getId(props.id, this.defaultId);
        this.state = {
            uuid: uuid,
            checked: props.checked,
            doValidate: !props.disabled || false,
            type: props.type ? props.type : 'checkbox'
        };
    }

    componentDidMount() {
        this.validate(this.state.checked ? 'true' : '')
    }

    componentWillReceiveProps(nextProps: PropsTypes) {
        if (nextProps.checked !== this.props.checked) {
            this.setState({
                checked: nextProps.checked
            })
        }
    }

    handleCheck = () => {
        if (this.props.disabled) return;

        this.setState({
            checked: !this.state.checked,
        }, () => {
            this.validate(this.state.checked ? 'true' : '');
            this.props.onChange && this.props.onChange(this.state.checked)
        })

    };

    public render(): JSX.Element {

        const {checked, uuid, type} = this.state;
        const {color, size, disabled,caption} = this.props;

        const uiClass = classNames(`is-checkradio is-${size || 'small'} is-${color || 'info'}`, {
                'disabled': disabled || this.readOnly(),
                'has-background-color': true,
            });

        return (
            <div className="krax-field">
                <input
                    className={uiClass}
                    id={`checkbox-${uuid}`}
                    name={this.props.name}
                    type={type}
                    checked={checked}
                    onChange={() => this.handleCheck()}
                    disabled={disabled}
                    readOnly={this.readOnly()}
                />
                <label htmlFor={`checkbox-${uuid}`}>{caption}</label>
                {RenderHtml.renderError(this.error())}
            </div>
        );
    }
}
