<template>
  <div class="license-activation public-page">
    <header class="info-header">
      <p class="info-header__text small-emph">Für <span class="info-header__emph">{{ me.email }}</span> haben wir keine
      gültige Lizenz gefunden</p>
    </header>
    <section class="coupon">
      <ValidationObserver
        v-slot="{handleSubmit, invalid}"
      >
        <form
          class="license-activation__form license-activation-form"
          novalidate
          @submit.prevent="handleSubmit(validateBeforeSubmit)">
          <h2>Geben Sie einen Coupon-Code ein</h2>
          <validated-input
            v-model="coupon"
            :remote-errors="couponErrors"
            rules="required"
            name="coupon"
            label="Coupon-Code"
            data-cy="coupon-input"
            class="login-form__field"
            tabindex="0"
          />
          <div class="actions">
            <loading-button
              :loading="loading"
              :disabled="invalid"
              class="actions__submit"
              data-cy="coupon-button"
              label="Coupon abschicken"
            />
            <a
              class="button button--big"
              data-cy="license-activation-cancel"
              @click="logout">Abmelden
            </a>
          </div>
        </form>
      </ValidationObserver>
    </section>
    <section class="get-license">
      <h2>Oder, kaufen Sie eine Lizenz</h2>
      <ul class="license-links">
        <li class="license-links__item"><a
          :href="teacherEditionUrl"
          class="hep-link">{{ pageTitle }} für Lehrpersonen</a></li>
        <li class="license-links__item"><a
          :href="studentEditionUrl"
          class="hep-link">{{ pageTitle }} für Lernende</a></li>
      </ul>
    </section>
  </div>
</template>

<script>

  import REDEEM_COUPON from '@/graphql/gql/mutations/redeemCoupon.gql';
  import ME_QUERY from '@/graphql/gql/queries/meQuery.gql';
  import LoadingButton from '@/components/LoadingButton';
  import ValidatedInput from '@/components/validation/ValidatedInput';
  import {ValidationObserver} from 'vee-validate';

  import me from '@/mixins/me';
  import logout from '@/mixins/logout';
  import pageTitleMixin from '@/mixins/page-title';

  export default {
    mixins: [me, logout, pageTitleMixin],
    components: {
      LoadingButton,
      ValidationObserver,
      ValidatedInput,
    },

    data() {
      return {
        coupon: '',
        couponErrors: [],
        loginError: '',
        submitted: false,
        me: {
          email: '',
        },
        teacherEditionUrl: `${process.env.HEP_URL}/myskillbox-lehrpersonen`,
        studentEditionUrl: `${process.env.HEP_URL}/myskillbox-fur-lernende`,
        loading: false,
      };
    },
    methods: {
      validateBeforeSubmit() {
        this.submitted = true;
        this.loading = true;
        this.$apollo.mutate({
          mutation: REDEEM_COUPON,
          variables: {
            input: {
              couponCode: this.coupon,
            },
          },
          update(
            store,
            {
              data: {coupon},
            },
          ) {
            if (coupon.success) {
              this.loading = false;
              this.couponErrors = [];
              this.$apollo.query({
                query: ME_QUERY,
                fetchPolicy: 'network-only',
              }).then(() => this.$router.push('/'));
            }
          },
        }).catch(({message}) => {
            this.loading = false;
            if (message.indexOf('invalid_coupon') > -1) {
              this.couponErrors = ['Der angegebene Coupon-Code ist ungültig.'];
            } else {
              this.couponErrors = ['Es ist ein Fehler aufgetreten. Bitte versuchen Sie es nochmals oder kontaktieren Sie den Administrator.'];
            }
          })
          .finally(() => {
            this.loading = false;
          });
      },
    },
  };
</script>

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

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

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

  .get-license {
    margin-top: $large-spacing
  }

  .license-links {
    &__item {
      margin-bottom: $medium-spacing;
    }
  }

</style>
