<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">
      <v-form
        class="license-activation__form license-activation-form"
        novalidate
        @submit="validateBeforeSubmit"
      >
        <h2 class="license-activation__heading">Geben Sie einen Coupon-Code ein</h2>
        <Field
          :rules="required"
          name="coupon"
          class="login-form__field"
          label="Coupon-Code"
          v-slot="{ field }"
        >
          <input-wrapper
            v-slot="{ id }"
            label="Coupon-Code"
            id="coupon"
          >
            <input
              v-bind="field"
              class="skillboxform-input__input skillbox-input"
              data-cy="coupon-input"
              name="coupon"
              :id="id"
            />
            <ErrorMessage
              name="coupon"
              data-cy="coupon-local-errors"
              class="skillboxform-input__error"
            />
          </input-wrapper>
        </Field>
        <div class="actions">
          <loading-button
            :loading="loading"
            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>
      </v-form>
      <div v-if="couponErrors.length">
        <small
          data-cy="coupon-remote-errors"
          class="skillboxform-input__error"
          v-for="error in couponErrors"
          :key="error"
          >{{ error }}</small
        >
      </div>
    </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"
            >{{ $flavor.textAppName }} für Lehrpersonen</a
          >
        </li>
        <li class="license-links__item">
          <a
            :href="studentEditionUrl"
            class="hep-link"
            >{{ $flavor.textAppName }} für Lernende</a
          >
        </li>
      </ul>
    </section>
  </div>
</template>

<script>
import { defineComponent } from 'vue';
import REDEEM_COUPON from '@/graphql/gql/mutations/redeemCoupon.gql';
import ME_QUERY from '@/graphql/gql/queries/meQuery.gql';
import LoadingButton from '@/components/LoadingButton.vue';

import me from '@/mixins/me';
import logout from '@/mixins/logout';

import { Form, Field, ErrorMessage } from 'vee-validate';
import InputWrapper from '@/components/validation/InputWrapper.vue';

export default defineComponent({
  mixins: [me, logout],
  components: {
    InputWrapper,
    LoadingButton,
    ErrorMessage,
    'v-form': Form,
    Field,
  },

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

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

.license-activation {
  &__heading {
    margin-bottom: $small-spacing;
  }

  &__license-info {
    margin-bottom: $medium-spacing;
  }
}

.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>
