<template>
  <div class="itf-wizard-step" :data-test="`itf-wizard-step-${id}`">
    <itf-form ref="form" v-model="valid">
      <slot name="card"
            :totalSteps="totalSteps"
            :currentStepIndex="currentStepIndex"
            :goPrevStep="goPrevStep"
            :goNextStep="goNextStep"
            :hasPrev="hasPrev"
            :hasNext="hasNext"
            :doValidation="doValidation"
            :isPending="isPending"
            :hasSaveForLater="hasSaveForLater"
            :isFromTalentScout="isFromTalentScout"
            :submitStep="submitStep"
      >
        <div class="step-manager-modal"
             :class="{'modal modal-sticky d-block': $mq === 'xs' || $mq === 'sm'}">
          <div class="modal-content" :class="{'overflow-y-auto': $mq === 'xs' || $mq === 'sm'}">
            <slot name="header"
                  :currentStepIndex="currentStepIndex"
                  :totalSteps="totalSteps"
                  :cardTitle="cardTitle"
            >
              <div class="modal-header d-flex align-items-center">
                <div>
                  <h2 class="modal-title" data-test="step-title">
                    {{ cardTitle }}
                  </h2>
                  <div class="text-muted">
                    {{ currentStepIndex + 1 }} of {{ totalSteps + 1 }}
                  </div>
                </div>
                <slot name="header-extra"/>
              </div>
              <up-fe-progress class="m-0-bottom d-md-none" :value="currentStepIndex"
                              :max="totalSteps" hide-details/>
            </slot>

            <div v-loading="isPending"
                 class="modal-flex-container flex-1"
                 :class="{'overflow-y-auto': $mq === 'xs' || $mq === 'sm'}"
            >
              <div class="modal-body" data-test="content" :class="{'flex-content': flexContent}">
                <slot name="step-body"
                      :totalSteps="totalSteps"
                      :currentStepIndex="currentStepIndex"
                      :goPrevStep="goPrevStep"
                      :goNextStep="goNextStep"
                      :hasPrev="hasPrev"
                      :hasNext="hasNext"
                      :doValidation="doValidation"
                      :isPending="isPending"
                >
                  <div class="modal-body-content">
                    <slot/>
                  </div>
                  <div class="modal-body-bottom">
                    <slot name="modal-body-bottom"/>
                  </div>
                </slot>
              </div>
            </div>

            <slot name="footer"
                  :goPrevStep="goPrevStep"
                  :goNextStep="goNextStep"
                  :hasPrev="hasPrev"
                  :hasNext="hasNext"
                  :submitStep="submitStep"
                  :doValidation="doValidation"
                  :isPending="isPending"
            >
              <div class="modal-footer">
                <div class="up-btn-row btn-row">
                  <itf-button
                    secondary
                    v-if="hasPrev"
                    :disabled="isPending"
                    data-test="step-back-button"
                    @click="goPrevStep">
                    Back
                  </itf-button>

                  <itf-button
                    primary
                    v-if="hasNext"
                    :disabled="isPending"
                    data-test="step-next-button"
                    @click="submitStep"
                  >
                    {{ nextCaption }}
                  </itf-button>
                </div>
              </div>
            </slot>
          </div>
        </div>
      </slot>
    </itf-form>
  </div>
</template>
<script>
import { Vue, Component, Prop, Emit, Inject } from 'vue-property-decorator';
import itfForm from '../form/Form';
import itfButton from '../button/Button';
import loading from '../../directives/loading';

export default @Component({
  name: 'itfWizardStep',
  components: {
    itfButton,
    itfForm,
  },
  directives: {
    loading
  },
  provide() {
    return { step: this }; // do not use Provide from vue-property-decorator
  }
})
class itfWizardStep extends Vue {
  @Inject({ default: null }) upApp;
  @Inject() stepsManager;

  @Prop() id;
  @Prop() cardTitle;
  @Prop({ type: String, default: 'Next' }) nextCaption;
  @Prop(Boolean) hasPrev;
  @Prop(Boolean) hasNext;
  @Prop(Boolean) sidebar;
  @Prop(Number) totalSteps;
  @Prop(Number) currentStepIndex;
  @Prop() submitFunc;
  @Prop(Boolean) hasSaveForLater;
  @Prop(Boolean) isFromTalentScout;
  @Prop(Boolean) hideSidebar;
  @Prop(String) url;
  @Prop({ type: Boolean, default: false }) flexContent;

  valid = false;

  mounted() {
    this.updatePageTitle();
  }

  updatePageTitle() {
    if (typeof document !== 'undefined') {
      document.title = this.cardTitle;
      document.querySelector('title').innerHTML = this.cardTitle;
    }
  }

  get isPending() {
    return this.stepsManager.getPending();
  }

  @Emit('next-step')
  goNextStep(completed = false) {
    this.stepsManager.goNextStep(completed);
    this.updatePageTitle();
  }

  @Emit('prev-step')
  goPrevStep() {
    this.stepsManager.goPrevStep();
    this.updatePageTitle();
  }

  @Emit('error-submit')
  formHasErrors() {
  }

  doValidation() {
    return this.$refs.form.doValidation();
  }

  async submitStep() {
    if (!this.$refs.form.doValidation()) {
      return this.formHasErrors();
    }

    this.stepsManager.setPending(true);

    try {
      if (this.submitFunc) {
        await this.submitFunc();
      }

      this.goNextStep(true);
    } catch (err) {
      this.handleError(err);
    }

    this.stepsManager.setPending(false);
  }

  handleError(err) {
    const errResponse = err.response && err.response.data && err.response.data.userError;

    if (this.upApp) {
      this.upApp.inlineAlert(
        errResponse || ('Sorry, something went wrong. Please try again or ' +
          '<a href="https://support.upwork.com/anonymous_requests/new" target="_blank">contact support</a>.'), {
          type: 'danger',
          timeout: 5000
        });
    }
  }
}
</script>
