<template>
  <div class="hello public-page">
    <h1 class="hello__title public-page__title">Wollen sie mySkillbox jetzt im Unterricht verwenden</h1>
    <form class="hello__form hello-form" novalidate @submit.prevent="validateBeforeSubmit">
      <div class="hello-form__field skillboxform-input">
        <label for="email" class="skillboxform-input__label">E-Mail</label>
        <input
          id="email"
          name="email"
          type="email"
          v-model="email"
          v-validate="'required'"
          data-vv-as="E-Mail"
          :class="{ 'skillboxform-input__input--error': errors.has('email') }"
          class="change-form__email skillbox-input skillboxform-input__input"
          autocomplete="off"
          data-cy="email-input"
          tabindex="0"
        />
        <small
          v-if="errors.has('email') && submitted"
          class="skillboxform-input__error"
          data-cy="email-local-errors"
        >{{ errors.first('email') }}</small>
        <small
          v-for="error in emailErrors"
          :key="error"
          class="skillboxform-input__error"
          data-cy="email-remote-errors"
        >{{ error }}</small>
      </div>
      <div class="actions">
        <button class="button button--primary button--big actions__submit" data-cy="hello-button">Los geht's</button>
      </div>
    </form>
  </div>
</template>

<script>

import {emailExists} from '../hep-client/index';
import HELLO_EMAIL_MUTATION from '@/graphql/gql/local/mutations/helloEmail.gql';

export default {
  components: {},

  methods: {
    validateBeforeSubmit() {
      this.$validator.validate().then(result => {
        this.submitted = true;
        if (result) {
          emailExists(this.email).then((response) => {
            let redirectRouteName = 'login';

            if (response.data) {
              redirectRouteName = 'registration';
            }

            this.$apollo.mutate({
              mutation: HELLO_EMAIL_MUTATION,
              variables: {
                helloEmail: this.email
              }
            })

            this.$router.push({name: redirectRouteName});
          })
          .catch(() => {
            this.registrationError = 'Es ist ein Fehler aufgetreten. Bitte versuchen Sie nochmals.';
          });
        }
      });
    },
    resetForm() {
      this.email = '';
      this.submitted = false;
      this.$validator.reset();
    }
  },

  data() {
    return {
      email: '',
      emailErrors: [],
      submitted: false
    };
  },
};
</script>

<style scoped lang="scss">
@import "@/styles/_variables.scss";
@import "@/styles/_mixins.scss";

.text-link {
  font-family: $sans-serif-font-family;
  color: $color-brand;
}

.actions {
  &__reset {
    display: inline-block;
    margin-left: $large-spacing;
  }
}

</style>
