<template>
  <div class="registration public-page">
    <header class="info-header">
      <p class="info-header__text small-emph">Für <span class="info-header__emph">{{ helloEmail }}</span> haben wir kein
      Hep Konto gefunden.</p>
      <h1
        class="registration__title public-page__title"
        data-cy="registration-title">Damit Sie {{ pageTitle }} verwenden können, müssen Sie ein Konto erstellen.</h1>
    </header>
    <form
      class="registration__form registration-form"
      novalidate
      @submit.prevent="validateBeforeSubmit">
      <div class="registration-form__field skillboxform-input">
        <div class="registration-form__field skillboxform-input">
          <label
            for="prefix"
            class="skillboxform-input__label">Anrede</label>
          <select
            v-model="prefix"
            v-validate="'required'"
            :class="{ 'skillboxform-input__input--error': errors.has('prefix') }"
            name="prefix"
            data-vv-as="Prefix"
            class="change-form__prefix skillbox-input skillboxform-input__input skillbox-dropdown"
            autocomplete="off"
            data-cy="prefix-selection"
            id="prefix"
          >
            <option
              value="Herr"
              selected>Herr
            </option>
            <option value="Frau">Frau</option>
          </select>
        </div>
        <label
          for="firstname"
          class="skillboxform-input__label">Vorname</label>
        <input
          v-model="firstname"
          v-validate="'required'"
          :class="{ 'skillboxform-input__input--error': errors.has('firstname') }"
          name="firstname"
          type="text"
          data-vv-as="Vorname"
          class="change-form__firstname skillbox-input skillboxform-input__input"
          autocomplete="off"
          data-cy="firstname-input"
          id="firstname"
        >
        <small
          class="skillboxform-input__error"
          data-cy="firstname-local-errors"
          v-if="errors.has('firstname') && submitted"
        >{{ errors.first('firstname') }}</small>
        <small
          :key="error"
          class="skillboxform-input__error"
          data-cy="firstname-remote-errors"
          v-for="error in firstnameErrors"
        >{{ error }}</small>
      </div>
      <div class="change-form__field skillboxform-input">
        <label
          for="lastname"
          class="skillboxform-input__label">Nachname</label>
        <input
          v-model="lastname"
          v-validate="'required'"
          :class="{ 'skillboxform-input__input--error': errors.has('lastname') }"
          name="lastname"
          type="text"
          data-vv-as="Nachname"
          class="change-form__new skillbox-input skillboxform-input__input"
          autocomplete="off"
          data-cy="lastname-input"
          id="lastname"
        >
        <small
          class="skillboxform-input__error"
          data-cy="lastname-local-errors"
          v-if="errors.has('lastname') && submitted"
        >{{ errors.first('lastname') }}</small>
        <small
          :key="error"
          class="skillboxform-input__error"
          data-cy="lastname-remote-errors"
          v-for="error in lastnameErrors"
        >{{ error }}</small>
      </div>
      <div class="change-form__field skillboxform-input">
        <label
          for="street"
          class="skillboxform-input__label">Strasse</label>
        <input
          v-model="street"
          v-validate="'required'"
          :class="{ 'skillboxform-input__input--error': errors.has('street') }"
          name="street"
          type="text"
          data-vv-as="Strasse"
          class="change-form__new skillbox-input skillboxform-input__input"
          autocomplete="off"
          data-cy="street-input"
          id="street"
        >
        <small
          class="skillboxform-input__error"
          data-cy="street-local-errors"
          v-if="errors.has('street') && submitted"
        >{{ errors.first('street') }}</small>
        <small
          :key="error"
          class="skillboxform-input__error"
          data-cy="street-remote-errors"
          v-for="error in streetErrors"
        >{{ error }}</small>
      </div>
      <div class="change-form__field skillboxform-input">
        <label
          for="city"
          class="skillboxform-input__label">Ort</label>
        <input
          v-model="city"
          v-validate="'required'"
          :class="{ 'skillboxform-input__input--error': errors.has('city') }"
          name="city"
          type="text"
          data-vv-as="Ort"
          class="change-form__new skillbox-input skillboxform-input__input"
          autocomplete="off"
          data-cy="city-input"
          id="city"
        >
        <small
          class="skillboxform-input__error"
          data-cy="city-local-errors"
          v-if="errors.has('city') && submitted"
        >{{ errors.first('city') }}</small>
        <small
          :key="error"
          class="skillboxform-input__error"
          data-cy="city-remote-errors"
          v-for="error in cityErrors"
        >{{ error }}</small>
      </div>
      <div class="change-form__field skillboxform-input">
        <label
          for="postcode"
          class="skillboxform-input__label">Postleitzahl</label>
        <input
          v-model="postcode"
          v-validate="'required'"
          :class="{ 'skillboxform-input__input--error': errors.has('postcode') }"
          name="postcode"
          type="text"
          data-vv-as="Postleitzahl"
          class="change-form__new skillbox-input skillboxform-input__input"
          autocomplete="off"
          data-cy="postcode-input"
          id="postcode"
        >
        <small
          class="skillboxform-input__error"
          data-cy="postcode-local-errors"
          v-if="errors.has('postcode') && submitted"
        >{{ errors.first('postcode') }}</small>
        <small
          :key="error"
          class="skillboxform-input__error"
          data-cy="postcode-remote-errors"
          v-for="error in postcodeErrors"
        >{{ error }}</small>
      </div>
      <div class="change-form__field skillboxform-input">
        <label
          for="password"
          class="skillboxform-input__label">Passwort</label>
        <input
          v-model="password"
          v-validate="'required|strongPassword'"
          :class="{ 'skillboxform-input__input--error': errors.has('password') && submitted }"
          name="password"
          type="text"
          data-vv-as="Passwort"
          class="change-form__new skillbox-input skillboxform-input__input"
          autocomplete="off"
          data-cy="password-input"
          id="password"
          ref="password"
        >
        <small
          class="skillboxform-input__error"
          data-cy="password-local-errors"
          v-if="errors.has('password') && submitted"
        >{{ errors.first('password') }}</small>
      </div>
      <div class="change-form__field skillboxform-input">
        <label
          for="password2"
          class="skillboxform-input__label">Passwort wiederholen</label>
        <input
          v-model="passwordConfirmation"
          v-validate="'required|confirmed:password'"
          :class="{ 'skillboxform-input__input--error': errors.has('password-confirmation') && submitted }"
          name="password-confirmation"
          type="text"
          data-vv-as="Passwort wiederholen"
          class="change-form__new skillbox-input skillboxform-input__input"
          autocomplete="off"
          data-cy="passwordConfirmation-input"
          id="password-confirmation"
        >
        <small
          class="skillboxform-input__error"
          data-cy="passwordConfirmation-local-errors"
          v-if="errors.has('password-confirmation') && submitted"
        >{{ errors.first('password-confirmation') }}</small>
      </div>
      <div class="change-form__field skillboxform-input">
        <checkbox
          v-model="acceptedTerms"
          :checked="acceptedTerms"
          v-validate="'required:true'"
          :class="{ 'skillboxform-input__input--error': errors.has('accepted-terms') && submitted}"
          name="accepted-terms"
          class="skillboxform-input__checkbox"
          data-cy="acceptedTerms-input"
          id="accepted-terms"
        >
          <span>Hiermit akzeptiere ich die <a
            href="https://www.hep-verlag.ch/agb"
            target="_blank"
            class="hep-link">AGB</a> und
            <a
              href="https://www.hep-verlag.ch/datenschutz"
              target="_blank"
              class="hep-link">Datenschutzbestimmungen</a></span>
        </checkbox>
        <small
          class="skillboxform-input__error"
          data-cy="acceptedTerms-local-errors"
          v-if="errors.has('accepted-terms') && submitted"
        >Sie müssen hier zustimmen, damit Sie sich registrieren können.</small>
      </div>
      <div class="skillboxform-input">
        <small
          class="skillboxform-input__error"
          data-cy="registration-error"
          v-if="registrationError">{{ registrationError }}</small>
      </div>
      <div class="actions">
        <loading-button
          :loading="loading"
          class="actions__submit"
          label="Konto erstellen"
          data-cy="register-button"
        />
      </div>
    </form>
  </div>
</template>

<script>

  import HELLO_EMAIL from '@/graphql/gql/local/helloEmail.gql';
  import Checkbox from '@/components/ui/Checkbox';
  import LoadingButton from '@/components/LoadingButton';

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

  function initialData() {
    return {
      prefix: 'Herr',
      lastname: '',
      firstname: '',
      password: '',
      passwordConfirmation: '',
      street: '',
      postcode: '',
      city: '',
      acceptedTerms: false,
      firstnameErrors: '',
      lastnameErrors: '',
      emailErrors: '',
      passwordsErrors: [],
      passwordErrors: [],
      streetErrors: [],
      cityErrors: [],
      postcodeErrors: [],
      registrationError: '',
      acceptedTermsError: [],
      submitted: false,
    };
  }

  export default {

    mixins: [pageTitleMixin],
    components: {
      LoadingButton,
      Checkbox
    },

    data() {
      return Object.assign(
        {
          helloEmail: '',
          loading: false,
        },
        initialData()
      );
    },

    methods: {
      validateBeforeSubmit() {
        this.$validator.validate().then(result => {
          this.submitted = true;
          if (result) {
            this.loading = true;
            const registrationData = {
              customer: {
                prefix: this.prefix,
                email: this.helloEmail,
                firstname: this.firstname,
                lastname: this.lastname,
                gender: this.prefix === 'Herr' ? 1 : 2,
                addresses: [{
                  street: [this.street],
                  postcode: this.postcode,
                  city: this.city,
                  country_id: 'CH',
                  firstname: this.firstname,
                  lastname: this.lastname,
                  prefix: this.prefix,
                  default_shipping: true,
                  default_billing: true
                }]
              },
              password: this.password,
              accepted_terms: this.acceptedTerms
            };

            // register(registrationData).then((response) => {
            //   this.loading = false;
            //   if (response.data.id && response.data.id > 0) {
            //     this.$router.push({name: 'checkEmail'});
            //   }
            // })
            //   .catch((error) => {
            //     this.loading = false;
            //     console.warn(error);
            //     if (error.response.data.message) {
            //       switch (error.response.data.message) {
            //         case 'Ein Kunde mit der gleichen E-Mail-Adresse existiert bereits in einer zugeordneten Website.':
            //           this.emailErrors = ['Die angegebene E-Mail ist bereits registriert.'];
            //           break;
            //         case 'Sie müssen hier zustimmen, damit Sie sich registrieren können.':
            //           this.acceptedTermsError = ['Sie müssen hier zustimmen, damit Sie sich registrieren können.'];
            //           break;
            //         default:
            //           this.registrationError = 'Es ist ein Fehler aufgetreten. Bitte versuchen Sie nochmals.';
            //       }
            //     } else {
            //       this.registrationError = 'Es ist ein Fehler aufgetreten. Bitte versuchen Sie nochmals.';
            //     }
            //   });
          }
        });
      },
      resetForm() {
        Object.assign(this.$data, initialData());
        this.$validator.reset();
      }
    },

    apollo: {
      helloEmail: {
        query: HELLO_EMAIL,
        result({data}) {
          if (data.helloEmail && data.helloEmail.email === '') {
            this.$router.push({name: 'hello'});
          }
        },
        update(data) {
          return data.helloEmail.email;
        },
        error() {
          console.log('error');
          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 {
    &__reset {
      display: inline-block;
      margin-left: $large-spacing;
    }
  }

  .registration {
    &__text {
      font-family: $sans-serif-font-family;
      margin-bottom: $small-spacing;
    }
  }

</style>
