<template>
  <div class="login public-page">
    <h1 class="login__title public-page__title">Melden Sie sich jetzt an</h1>
    <ValidationObserver v-slot="{invalid, handleSubmit}">
      <form
        class="login__form login-form"
        novalidate
        @submit.prevent="handleSubmit(validateBeforeSubmit)">

        <validated-input
          v-model="email"
          :remote-errors="emailErrors"
          rules="required"
          name="email"
          label="E-Mail"
          data-cy="email-input"
          id="email"
        />

        <validated-input
          v-slot="{errors}"
          v-model="password"
          :remote-errors="passwordErrors"
          label="Passwort"
          rules="required"
          name="password"
          type="password"
          data-cy="password-input"
        />

        <div class="skillboxform-input">
          <small
            class="skillboxform-input__error"
            data-cy="login-error"
            v-if="loginError">{{ loginError }}</small>
        </div>
        <div class="actions">
          <button
            :disabled="invalid"
            class="button button--primary button--big actions__submit"
            data-cy="login-button">Anmelden
          </button>
        </div>
      </form>
    </ValidationObserver>
  </div>
</template>

<script>
  import BETA_LOGIN_MUTATION from '@/graphql/gql/mutations/betaLogin.gql';
  import {ValidationObserver, ValidationProvider} from 'vee-validate';
  import ValidatedInput from '@/components/validation/ValidatedInput';

  export default {
    components: {
      ValidatedInput,
      ValidationProvider,
      ValidationObserver,
    },

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

    methods: {
      validateBeforeSubmit() {
        this.submitted = true;

        const variables = {
          input: {
            usernameInput: this.email,
            passwordInput: this.password,
          },
        };

        const redirectUrl = this.$route.query.redirect ? this.$route.query.redirect : '/';

        this.$apollo.mutate({
          client: 'publicClient',
          mutation: BETA_LOGIN_MUTATION,
          variables,
          update: (store, {data: {betaLogin}}) => {
            try {
              if (betaLogin.success) {
                console.log(this);
                this.$router.push(redirectUrl);
              }
            } catch (e) {
              console.warn(e);
              this.loginError = 'Es ist ein Fehler aufgetreten. Bitte versuchen Sie nochmals.';
            }
          },
        }).catch(error => {
          const firstError = error.graphQLErrors[0];
          switch (firstError.message) {
            case 'invalid_credentials':
              this.loginError = 'Die E-Mail oder das Passwort ist falsch. Bitte versuchen Sie nochmals.';
              break;
            case 'license_inactive':
              this.loginError = 'Ihre Lizenz ist nicht mehr aktiv.';
              break;
          }
        });
      },
    },
  };
</script>

<style scoped lang="scss">
  @import "~styles/helpers";

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

  .actions {

    display: flex;
    justify-content: space-between;

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

</style>
