<template>
  <div class="login public-page">
    <h1 class="login__title public-page__title">Melden Sie sich jetzt an</h1>
    <v-form
      class="login__form login-form"
      novalidate
      @submit="validateBeforeSubmit"
    >
      <Field
        :rules="required"
        name="email"
        label="E-Mail"
        class="login-form__field"
        v-slot="{ field }"
      >
        <input-wrapper
          v-slot="{ id }"
          label="E-Mail"
          id="email"
        >
          <input
            v-bind="field"
            class="skillboxform-input__input skillbox-input"
            data-cy="email-input"
            name="email"
            :id="id"
          />
          <ErrorMessage
            name="email"
            data-cy="email-local-errors"
            class="skillboxform-input__error"
          />
        </input-wrapper>
      </Field>
      <Field
        :rules="required"
        name="password"
        class="login-form__field"
        label="Passwort"
        v-slot="{ field }"
      >
        <input-wrapper
          v-slot="{ id }"
          label="Passwort"
          id="password"
        >
          <input
            v-bind="field"
            data-cy="password-input"
            class="skillboxform-input__input skillbox-input"
            name="password"
            type="password"
            :id="id"
          />
          <ErrorMessage
            name="password"
            data-cy="password-local-errors"
            class="skillboxform-input__error"
          />
        </input-wrapper>
      </Field>
      <div v-if="loginError">
        <small
          data-cy="login-error"
          class="skillboxform-input__error"
          >{{ loginError }}</small
        >
      </div>

      <div class="actions">
        <button
          class="button button--primary button--big actions__submit"
          data-cy="login-button"
        >
          Anmelden
        </button>
      </div>
    </v-form>
  </div>
</template>

<script>
import BETA_LOGIN_MUTATION from 'gql/public-client/betaLogin.gql';
import { Form, Field, ErrorMessage } from 'vee-validate';
import { defineComponent } from 'vue';
import InputWrapper from '@/components/validation/InputWrapper.vue';

export default defineComponent({
  components: {
    InputWrapper,
    'v-form': Form,
    Field,
    ErrorMessage,
  },

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

  methods: {
    required(value, { field }) {
      if (value && value.trim()) {
        return true;
      }
      return `${field} ist ein Pflichtfeld`;
    },
    validateBeforeSubmit({ email, password }) {
      this.submitted = true;

      const variables = {
        input: {
          usernameInput: email,
          passwordInput: 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>
