import * as React from 'react'


export const wizard = function({
  initialStep = 0,
  steps,
  submitStep = steps.length - 2,
}) {
  return (Comp) => {
    class RxWizardForm extends React.Component {
      static displayName = `QuarksWizard(${Comp.displayName || Comp.name})`

      steps = typeof steps === 'function' ? steps(this.props) : steps

      state = {
        currentStep: initialStep,
        formValue: {},
        submitted: false,
        totalSteps: this.steps.length,
      }

      constructor(props){
          super(props);

          this.goTo = this.goTo.bind(this);
          this.handleSubmit = this.handleSubmit.bind(this);
          this.handleGoBack = this.handleGoBack.bind(this);
          this.renderCurrentForm = this.renderCurrentForm.bind(this);
      }

      goTo() {
        this.setState({
          currentStep: step,
        })
      }

      handleSubmit(formValue) {
        const submitted = this.state.currentStep === submitStep
        const currentStep = submitted ? this.state.currentStep : this.state.currentStep + 1

        this.setState(
          {
            currentStep,
            formValue: {
              ...this.state.formValue,
              ...formValue,
            },
            submitted,
          },
          () => {
            if (submitted) {
              this.props.onSubmit(this.state.formValue)
            }
          },
        )
      }

      handleGoBack() {
        if (this.state.currentStep !== 0) {
          this.setState({
            currentStep: this.state.currentStep - 1,
          })
        }
      }

      renderCurrentForm() {
        const { currentStep, formValue } = this.state
        const FormComponent = this.steps[currentStep]

        return (
          <FormComponent
            {...this.props}
            {...formValue}
            goBack={this.handleGoBack}
            onSubmit={this.handleSubmit}
            onError={this.props.onError}
          />
        )
      }

      render() {
        return <Comp goTo={this.goTo} renderCurrentForm={this.renderCurrentForm} {...this.state} {...this.props} />
      }
    }

    return Wizard
  }
}
