import * as React from 'react';
import * as classNames from 'classnames';
import {Component, HTMLProps, MouseEvent} from 'react';
import {Button, Icon, JsonDebugger} from './';

export interface FormActionsProps {
  loadingStateActiveOnSubmitButton?: boolean;
  noBackButton?: boolean;
  noJsonDebugger?: boolean;
  noSubmitButton?: boolean;
  objectToDebug?: any;
  submitButtonDisabled?: boolean;
  onChangeDebugObject?: (object: any) => void;
  onClickBackButton?: (e: MouseEvent<HTMLButtonElement>) => void;
}

export interface FormActionsState {
  debugModeEnabled: boolean;
}

export class FormActions extends Component<FormActionsProps, FormActionsState> {
  static defaultProps: FormActionsProps = {
    loadingStateActiveOnSubmitButton: false,
    noBackButton: false,
    noJsonDebugger: false,
    noSubmitButton: false,
    objectToDebug: {},
    submitButtonDisabled: false,
    onChangeDebugObject: () => { return; },
    onClickBackButton: () => { return; },
  };

  state: FormActionsState = {
    debugModeEnabled: false,
  };

  render() {
    const {
      loadingStateActiveOnSubmitButton,
      noBackButton,
      noJsonDebugger,
      noSubmitButton,
      objectToDebug,
      submitButtonDisabled,
      onChangeDebugObject,
      onClickBackButton} = this.props;

    const {debugModeEnabled} = this.state;

    return (
      <div>
        <div className="form-group-submit">
          {!noBackButton && (
            <Button
              title="Go back"
              className="btn-link btn-icon"
              onClick={onClickBackButton}
            >
              <Icon name="arrow_back" />
            </Button>
          )}

          {!noSubmitButton && (
            <Button
              className={classNames(
                {'btn-loading': loadingStateActiveOnSubmitButton},
              )}
              color="primary"
              disabled={submitButtonDisabled || loadingStateActiveOnSubmitButton}
              size="lg"
              type="submit"
            >
              Save
            </Button>
          )}

          {!noJsonDebugger && (
            <Button
              className="btn-icon"
              color="link"
              onClick={this.toggleDebugMode}
            >
              <Icon name="code" />
            </Button>
          )}
        </div>

        {!noJsonDebugger && debugModeEnabled && (
          <div style={{marginTop: '1rem'}}>
            <JsonDebugger
              object={objectToDebug}
              onChange={onChangeDebugObject}
            />
          </div>
        )}
      </div>
    );
  }

  toggleDebugMode = () => {
    this.setState({debugModeEnabled: !this.state.debugModeEnabled});
  }
}
