<template>
  <div class="login public-page">
    <header class="info-header">
      <p class="info-header__text small-emph">Super, wir haben für <span
        class="info-header__emph">{{ helloEmail.email }}</span> ein hep-Konto gefunden.</p>
      <h1
        class="login__title public-page__title"
        data-cy="login-title">Bitte geben Sie das passende Passwort ein</h1>
    </header>
    <form
      class="login__form login-form"
      novalidate
      @submit.prevent="validateBeforeSubmit">
      <div class="change-form__field skillboxform-input">
        <label
          for="password"
          class="skillboxform-input__label">Passwort</label>
        <input
          v-model="password"
          v-validate="'required'"
          :class="{ 'skillboxform-input__input--error': errors.has('password') }"
          name="password"
          type="password"
          data-vv-as="Passwort"
          class="change-form__new skillbox-input skillboxform-input__input"
          autocomplete="off"
          data-cy="password-input"
          tabindex="0"
          id="password"
        >
        <small
          :key="error"
          class="skillboxform-input__error"
          data-cy="password-errors"
          v-for="error in passwordErrors"
        >{{ error }}</small>
      </div>
      <div class="actions">
        <loading-button
          :loading="loading"
          class="actions__submit"
          data-cy="login-button"
          label="Anmelden"
        />
        <router-link
          :to="{name: 'hello'}"
          tag="button"
          class="button button--big actions__submit back-button">Abbrechen
        </router-link>
        <router-link
          :to="{name: 'forgotPassword'}"
          class="actions__reset text-link">Passwort vergessen?</router-link>
      </div>
    </form>
  </div>
</template>

<script>

  import HELLO_EMAIL from '@/graphql/gql/local/helloEmail.gql';
  import LOGIN_MUTATION from '@/graphql/gql/mutations/login.gql';
  import LoadingButton from '@/components/LoadingButton';

  export default {
    components: {LoadingButton},

    data() {
      return {
        password: '',
        passwordErrors: [],
        submitted: false,
        loading: false
      };
    },

    methods: {
      validateBeforeSubmit() {
        // this.$validator.validate().then(result => {
        //   this.submitted = true;
        //   if (result) {
        //     this.loading = true;
        //     login(this.helloEmail.email, this.password)
        //       .then((response) => {
        //         this.loading = false;
        //         if (response.status === 200) {
        //           this.mySkillboxLogin(response.data);
        //         } else {
        //           this.passwordErrors = ['Es ist ein Fehler aufgetreten. Bitte versuchen Sie nochmals.'];
        //         }
        //       })
        //       .catch((error) => {
        //         this.loading = false;
        //         if (error.response.data.message && error.response.data.message === 'Sie haben sich nicht korrekt eingeloggt oder Ihr Konto ist vor\u00fcbergehend deaktiviert.') {
        //           this.passwordErrors = ['Die von Ihnen eingegebene E-Mail-Adresse und das Passwort passen nicht zusammen.'];
        //         } else {
        //           this.passwordErrors = ['Es ist ein Fehler aufgetreten. Bitte versuchen Sie nochmals.'];
        //         }
        //       });
        //   }
        // });
      },
      mySkillboxLogin(token) {
        const that = this;
        this.$apollo.mutate({
          client: 'publicClient',
          mutation: LOGIN_MUTATION,
          variables: {
            input: {
              tokenInput: token
            }
          },
          update(
            store,
            {
              data: {
                login
              }
            }
          ) {
            try {
              if (login.success) {
                if (login.message === 'no_valid_license') {
                  that.$router.push({name: 'licenseActivation'});
                } else {
                  const redirectUrl = that.$route.query.redirect ? that.$route.query.redirect : '/';
                  that.$router.push(redirectUrl);
                }
              }
            } catch (e) {
              that.passwordErrors = ['Es ist ein Fehler aufgetreten. Bitte versuchen Sie nochmals.'];
            }
          }
        })
          .catch(errors => {
            const firstError = errors.graphQLErrors[0];
            switch (firstError.message) {
              case 'invalid_credentials':
                that.passwordErrors = ['Die E-Mail oder das Passwort ist falsch. Bitte versuchen Sie nochmals.'];
                break;
              case 'email_not_verified':
                that.passwordErrors = ['Bitte verifiziere zuerst deine E-Mail.'];
                break;
              case 'no_valid_license':
                this.$router.push({name: 'licenseActivation'});
                break;
            }
          });
      },
      resetForm() {
        this.password = '';
        this.submitted = false;
        this.$validator.reset();
      },
    },

    apollo: {
      helloEmail: {
        query: HELLO_EMAIL,
        result({data: {helloEmail}}) {
          if (helloEmail.email === '') {
            this.$router.push({name: 'hello'});
          }
        }
      },
    },

  };
</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 {
    display: flex;

    &__reset {
      display: inline-block;
      margin-left: auto;
      line-height: 19px;;
      padding: $small-spacing;
    }
  }

  .back-button {
    //font-size: 1rem;
    line-height: normal;
    margin-left: $medium-spacing;
  }

</style>
