import React from 'react';
import Label from "@/jsx/Controls/Label.jsx";
import Helper from "@/jsx/Controls/Helper.jsx";
import Control from "@/jsx/Controls/Control.jsx";
import {cleanProps} from "@/js/Tools/cleanProps.js";

export default class CheckboxControl extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      value: null,
      checked: false,
      processing: false,
    };
  }

  componentDidMount() {
    const {value, processing} = this.props;
    this.setState({
      checked: value === 'true',
      processing: processing ?? false,
    });
  }

  componentDidUpdate(prevProps, prevState, snapshot) {

    // Is the value changed?
    const {value} = this.props;
    if (prevProps.value !== value) {
      this.setState({
        checked: value === 'true',
      });
    }

    // Is the processing changed?
    if (prevProps.processing !== this.props.processing) {
      this.setState({
        processing: this.props.processing ?? false
      });
    }

  }

  /**
   * Handle the change event
   */
  handleChange() {
    this.setState({
      checked: !this.state.checked,
    });

    // Process submit
    setTimeout(() => {
      this.handleSubmit();
    }, 1);
  }

  /**
   * Reset the value to the default value
   */
  handleReset() {

    const {default_value} = this.props;

    // Set default value in field
    this.setState({
      value: default_value,
      checked: default_value === 'true',
      disabled: false,
    });

    // Process submit
    setTimeout(() => {
      this.handleSubmit();
    }, 1);

  }

  /**
   * Handle the submitted event
   */
  handleSubmit() {

    this.props.handleSubmit({
      'name': this.props.name,
      'value': this.state.checked ? 'true' : 'false',
    });

  }

  render() {
    const {default_value, name, helper, label, disabled} = this.props;
    return (
      <div className="ra-settings-control">
        <Label {...this.props} processing={this.state.processing}>
          {label}
        </Label>
        <div className="ra-control-wrapper type-checkbox">
          <Control processing={this.state.processing}>
            <input
              {...cleanProps(this.props)}
              type="checkbox"
              id={name}
              autoComplete={name}
              value={this.state.value}
              checked={this.state.checked}
              onChange={this.handleChange.bind(this)}
              disabled={this.state.processing || disabled}
            />
          </Control>
          <Helper
            {...this.props}
            showReset={this.state.checked !== (default_value === 'true') && !disabled}
            onReset={this.handleReset.bind(this)}
            processing={this.state.processing}
          >
            {helper}
          </Helper>
        </div>
      </div>
    );

  }

}
