<template>
  <login-form-template v-bind="formTemplateProps">
    <div @keyup.13="submit">
      <b-row v-show="getErrors('login')">
        <b-alert variant="danger" show class="mb-0 w-100 text-break">
          {{ $t(getErrors('login')) }}
        </b-alert>
      </b-row>
      <b-row class="my-2">
        <b-col class="col-12">
          <div class="mb-1 d-flex flex-column">
            <b-form-input
              id="email"
              trim
              name="email"
              type="text"
              ref="email"
              v-model="email"
              v-validate="'required'"
              class="custom-form-field input order-1"
              :class="{ 'is-danger': errors.has('email') && passFlag }"
              data-qa="login-login-form-email-input"
              :data-vv-as="$t('Login.Landing.Form.MemberEmail.Label')"
              :placeholder="$t('Login.Landing.Form.MemberEmail.Placeholder')"
            />
            <label for="email" class="custom-form-label-tag custom-form-label pr-5 order-0">
              {{ $t('Login.Landing.Form.MemberEmail.Placeholder') }}
            </label>
          </div>
          <span v-show="errors.has('email') && passFlag" class="help text-danger" data-qa="login-login-form-error-msg">
            {{ errors.first('email') }}
          </span>
        </b-col>
      </b-row>
      <b-row class="my-2">
        <b-col class="col-12">
          <div class="mb-1 d-flex flex-column">
            <b-form-input
              id="password"
              trim
              v-model="password"
              v-validate="'required'"
              :class="{ 'is-danger': errors.has('password') && passFlag }"
              name="password"
              ref="password"
              type="password"
              class="custom-form-field input order-1"
              data-qa="login-login-form-password-input"
              :data-vv-as="$t('Login.Landing.Form.Password.Label')"
              :placeholder="$t('Login.Landing.Form.Password.Placeholder')"
            />
            <label for="password" class="custom-form-label-tag custom-form-label pr-5 order-0">
              {{ $t('Login.Landing.Form.Password.Placeholder') }}
            </label>
          </div>
          <span v-show="errors.has('password') && passFlag" class="help text-danger">
            {{ errors.first('password') }}
          </span>
        </b-col>
      </b-row>

      <b-row class="actions-group">
        <b-col cols="12" class="mb-4 forgot-password-button">
          <b-link :to="{ name: 'ForgotPassword' }">{{ $t('Login.LoginForm.ForgotPassword') }}</b-link>
        </b-col>
        <b-col cols="12" class="mb-4 login-button">
          <b-button
            block
            size="lg"
            @click="submit"
            variant="primary"
            ref="submitButton"
            @keyup.13="submit"
            data-qa="login-login-form-login-btn"
          >
            <b-spinner v-show="isLoading('login')" small />
            <span v-show="!isLoading('login')">{{ $t('Login.Landing.Form.Submit.Label') }}</span>
          </b-button>
        </b-col>
        <b-col v-if="isInlineEnrollment" cols="12" class="mb-4 enrolment-button">
          <label class="mr-1">{{ $t('Login.LoginForm.NewToElken') }}</label>
          <b-link ref="getStarted" :to="{ name: 'Enrolment' }">
            {{ $t('Login.LoginForm.GetStarted') }}
          </b-link>
        </b-col>
      </b-row>
    </div>

    <div v-if="displayFooter" class="justify-content-between d-xl-flex col-12" slot="footer">
      <div v-if="!isInlineEnrollment" class="d-flex d-xl-block justify-content-between mb-3 mb-xl-0 text-nowrap">
        <label class="mr-2 mt-2 mt-xl-0">{{ $t('Login.LoginForm.NewToElken') }}</label>
        <b-button variant="outline-primary" ref="getStarted" class="mr-2" :to="{ name: 'Enrolment' }">
          {{ $t('Login.LoginForm.GetStarted') }}
        </b-button>
      </div>
      <div class="mr-2 mr-md-0 d-flex d-xl-block justify-content-between mb-3 mb-xl-0 text-nowrap">
        <label class="mr-2">{{ $t('Common.Language') + ':' }} </label>
        <div
          class="d-inline-block v-align-bottom"
          :class="{ 'initializing-light-extra': isLoading(['loadingGeoCountry', 'loadLanguages']) }"
        >
          <b-select :options="getAllLanguages" v-model="selectedLanguage" id="language" class="w-auto" />
        </div>
      </div>
    </div>
  </login-form-template>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
import IBSLogo from '@/assets/img/img-ibslogo.png'
import LoginFormTemplate from './templates/FormTemplate'
import LoginRoutingMixing from './mixins/loginRoutingMixin'

export default {
  name: 'LoginForm',
  mixins: [LoginRoutingMixing],
  components: {
    LoginFormTemplate,
  },
  props: {
    namespace: {
      type: String,
      default: 'eshop',
    },
    disableLanguageSelection: {
      type: Boolean,
      default: false,
    },
    inlineEnrollment: {
      type: Boolean,
      default: false,
    },
    showFooter: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      email: '',
      password: '',
      selectedLanguage: null,
      ibsLogo: IBSLogo,
      passFlag: false,
      error: false,
      isTextLogin: true,
      isEvo: this.$appSettings.evo.enable,
    }
  },
  $_veeValidate: {
    validator: 'new',
  },
  async mounted() {
    if (!this.disableLanguageSelection) {
      await this.loadAllLanguages()
      this.afterLoading('loadingGeoCountry').then(process => {
        // Set default language based on country if user have not selected a language
        let selectedLanguageId = this.getSelectedLanguage.id
        if (this.$helpers.isEmpty(selectedLanguageId)) {
          this.selectedLanguage = this.getDefaultPreferredGeoLanguage.id
        } else {
          this.selectedLanguage = selectedLanguageId
        }
      })
    }
  },
  computed: {
    ...mapGetters([
      'isLoading',
      'getErrors',
      'getAllLanguages',
      'getSelectedLanguage',
      'getDefaultPreferredGeoLanguage',
      'getCurrentIPCountry',
      'afterLoading',
    ]),
    formTemplateProps() {
      let props = {
        showBack: false,
        namespace: this.namespace,
        showLogo: true,
        title: this.$t('Login.LoginForm.LoginTitle'),
        text: this.$t('Login.LoginForm.LoginText'),
      }

      if (this.isEvo) {
        props['showLogo'] = false
        props['namespace'] = 'evo'
        props['titleClass'] = ['font-size-2', 'text-black', 'font-weight-bold-semi']
        props['textClass'] = ['font-size-3', 'text-dark', 'font-weight-light']
      }

      return props
    },

    isInlineEnrollment() {
      return this.isEvo || this.inlineEnrollment
    },

    displayFooter() {
      return this.isEvo ? false : this.showFooter
    },
  },
  methods: {
    ...mapActions([
      'loginUser',
      'activateReset',
      'setResetStatus',
      'setResetResponseData',
      'loadAllLanguages',
      'updateSelectedLanguage',
    ]),
    submit: function() {
      let vue = this
      vue.error = false
      vue.isTextLogin = false
      vue.passFlag = true
      this.$validator.validateAll().then(async valid => {
        if (valid) {
          await vue.loginUser({ email: vue.email, password: vue.password })
          vue.$emit('callback')
        }
      })
    },
  },
  watch: {
    selectedLanguage(value) {
      if (typeof value === 'number') {
        this.updateSelectedLanguage(value)
      }
    },
  },
}
</script>
