<template>
  <login-form-template v-bind="formTemplateProps" @onBack="activateReset(false)">
    <b-container @keyup.13="handleEnterKeyboard" class="px-0">
      <b-row v-if="getResetErrorStatus" class="m-0">
        <b-alert
          :variant="namespace !== 'byDzyne' ? 'success' : 'danger'"
          v-if="getResetErrorMessage !== null"
          show
          class="reset-alert col"
        >
          <span v-for="(error, key) in getResetErrorMessage" :key="`error-${key}`">
            {{ error }}
          </span>
        </b-alert>
        <b-alert :variant="namespace !== 'byDzyne' ? 'success' : 'danger'" v-else show class="reset-alert">
          {{
            $t('Login.LoginForm.ResetErrorMessage', {
              user:
                selected === 'mobile'
                  ? phoneNumber(getEmailReset.mobile_country_code_id, getEmailReset.mobile_num)
                  : getEmailReset.old_member_id,
            })
          }}
        </b-alert>
      </b-row>
      <b-row class="my-0">
        <b-col cols="12">
          <b-form-group ref="forgotPasswordType">
            <b-form-radio-group v-model="selected" :options="options" name="radio-options"></b-form-radio-group>
          </b-form-group>
        </b-col>
      </b-row>
      <b-row v-if="selected === 'member'" class="mt-0">
        <b-col class="col-12 mb-2" v-if="selected === 'member'">
          <b-form-input
            v-model="memberId"
            v-validate="'required|min:7'"
            :class="{ input: true, 'is-danger': errors.has('Member ID') && showValidationErrors }"
            name="Member ID"
            type="text"
            key="member-input"
            ref="memberId"
            :placeholder="$t('Login.Landing.Form.Member.Placeholder')"
          />
          <span v-show="errors.has('Member ID') && showValidationErrors" class="help text-danger">
            {{ errors.first('Member ID') }}
          </span>
        </b-col>
      </b-row>
      <b-row v-else-if="selected === 'email'" class="mt-0">
        <b-col class="col-12 mb-2">
          <b-form-input
            v-model="emailAddress"
            v-validate="'required|email'"
            :class="{ input: true, 'is-danger': errors.has('Email') && showValidationErrors }"
            name="Email"
            type="text"
            key="email-input"
            ref="email"
            :placeholder="$t('Login.Landing.Form.Email.Placeholder')"
          />
          <span v-show="errors.has('Email') && showValidationErrors" class="help text-danger">
            {{ errors.first('Email') }}
          </span>
        </b-col>
      </b-row>
      <b-row v-else>
        <b-col class="col-12 col-lg-4 mb-2 pr-lg-0">
          <b-form-select
            v-model="mobileCountryCodeId"
            v-validate="'required'"
            :class="{ input: true, 'border-danger': errors.has('mobile country code') && showValidationErrors }"
            name="mobile country code"
            ref="mobileCountryCodeId"
          >
            <option value="null" disabled>
              {{ $t('Eshop.Order.GlobalWords.Select') }}
            </option>
            <option v-for="(item, idx) in callCodeList" :value="item.value" :key="idx">
              {{ item.text }}
            </option>
          </b-form-select>
          <span v-show="errors.has('mobile country code') && showValidationErrors" class="help text-danger">
            {{ errors.first('mobile country code') }}
          </span>
        </b-col>
        <b-col class="col-12 col-lg-8 pl-lg-1">
          <b-form-input
            v-validate="'required|numeric'"
            name="Phone Number"
            v-model="mobilePhoneNumber"
            :class="{ input: true, 'border-danger': errors.has('Phone Number') && showValidationErrors }"
            placeholder="e.g. 123456789"
            type="number"
            key="mobile-input"
            ref="phoneNumber"
          />
          <span v-show="errors.has('Phone Number') && showValidationErrors" class="help text-danger">
            {{ errors.first('Phone Number') }}
          </span>
        </b-col>
      </b-row>
      <b-row class="mt-2 mb-3">
        <b-col cols="12" class="justify-content-end login-column-reset px-3 row">
          <b-row align-h="end">
            <b-button ref="submitButton" @click="handleEnterKeyboard" @keyup.13="handleEnterKeyboard" class="py-2">
              <b-spinner v-show="isLoading('resetpassword')" small class="mx-4" />
              <span v-show="!isLoading('resetpassword')">{{ $t('Login.LoginForm.SendReset') }}</span>
            </b-button>
          </b-row>
        </b-col>
      </b-row>
    </b-container>
  </login-form-template>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
import { PhoneMixin } from '@/app/_global/mixins'
import LoginFormTemplate from './templates/FormTemplate'
import LoginRoutingMixin from './mixins/loginRoutingMixin'

export default {
  name: 'ForgotPassword',
  components: {
    LoginFormTemplate,
  },
  mixins: [PhoneMixin, LoginRoutingMixin],
  props: {
    namespace: { type: String, default: 'eshop' },
  },
  data() {
    return {
      memberId: '',
      emailAddress: '',
      mobileCountryCodeId: null,
      mobilePhoneNumber: '',
      showValidationErrors: false,
      selected: 'member',
      options: [
        { text: this.$t('Login.Landing.Form.Member.Label'), value: 'member' },
        { text: this.$t('Login.Landing.Form.Email.Label'), value: 'email' },
        { text: this.$t('Login.Landing.Form.Mobile.Label'), value: 'mobile' },
      ],
      isEvo: this.$appSettings.evo.enable,
    }
  },
  $_veeValidate: {
    validator: 'new',
  },
  mounted() {},
  computed: {
    ...mapGetters([
      'getResetStatus',
      'getResetAlert',
      'getResetPasswordStatus',
      'getShowReset',
      'getEmailReset',
      'getResetErrorStatus',
      'getMemberDetails',
      'getErrors',
      'getResetErrorMessage',
      'isLoading',
    ]),
    formTemplateProps() {
      let props = {
        showBack: true,
        namespace: this.namespace,
        showLogo: true,
        title: this.$t('Login.LoginForm.ForgotPassword'),
        text: this.$t('Login.LoginForm.ForgotPasswordText'),
        'form-class': "['justify-content-start']",
      }

      if (this.isEvo) {
        props['showLogo'] = false
        props['namespace'] = 'evo'
      }

      return props
    },
  },
  methods: {
    ...mapActions(['sendResetLink', 'activateReset', 'setResetErrorStatus', 'setResetStatus', 'setResetResponseData']),
    handleEnterKeyboard() {
      this.$validator.validateAll().then(valid => {
        this.showValidationErrors = true
        if (valid) {
          this.showValidationErrors = false
          let query = { email: this.emailAddress }
          if (this.selected === 'member') {
            query = { old_member_id: this.memberId }
          } else if (this.selected === 'mobile') {
            query = {
              mobile_country_code_id: this.mobileCountryCodeId,
              mobile_num: this.mobilePhoneNumber,
            }
          }
          this.sendResetLink(query)
        }
      })
    },
  },
  watch: {
    selected() {
      this.setResetErrorStatus(false)
      this.memberId = ''
      this.emailAddress = ''
      this.mobileCountryCodeId = null
      this.mobilePhoneNumber = ''
      this.showValidationErrors = false
    },
  },
  created() {
    this.$validator.localize({
      en: {
        messages: {
          email: () => this.$t('Login.LoginForm.Validator.Email'),
        },
      },
    })
  },
}
</script>
