<template>
  <div>
    <b-row class="text-center ewallet-form-field">
      <b-col cols="12">
        <h1 class="mb-1">{{ $t('Common.Security.EnterVerificationCode') }}</h1>
        <p>
          <span>{{ $t('EWallet.Activation.CodeVerification.HelpText') }}</span>
          <span class="text-primary"> {{ getMaskedMobileNumber }}</span>
        </p>
      </b-col>

      <b-col cols="12" class="mt-4 mb-5">
        <b-row class="justify-content-center">
          <b-col cols="auto" class="mb-2">
            <!--TODO: improve UX by limiting only numeric input-->
            <b-form-input
              maxlength="6"
              class="rounded-1 text-center"
              :disabled="fieldsLock"
              name="Verification Code"
              placeholder="e.g. 123456"
              v-model="verificationCode"
              v-validate="'required|digits:6'"
              :data-vv-as="$t('Common.Security.VerificationCode')"
              :state="!(customError || errors.has('Verification Code')) && null"
              :data-qa="`${dataQaPrefix}-otpVerification-mobileNumber-input`"
            />
          </b-col>

          <b-col cols="12" class="text-danger mb-2">
            <div v-if="errors.has('Verification Code')">{{ errors.first('Verification Code') }}</div>
            <div v-if="customError" class="pre-wrap">{{ customError }}</div>
          </b-col>

          <b-col cols="auto" class="mb-2">
            <span>{{ $t('EWallet.ResendVerificationCode.label') }}</span>
            <b-button
              variant="link"
              class="text-primary"
              :disabled="resendCountdown > 0"
              @click="requestVerificationCode"
              :data-qa="`${dataQaPrefix}-otpVerification-resendVerificationCode-btn`"
            >
              <span v-show="resendCountdown === 0">{{ $t('EWallet.ResendVerificationCode') }}</span>
              <span v-show="resendCountdown">
                {{ $t('EWallet.ResendVerificationCodeIn', { timer: getCountdownTime }) }}
              </span>
            </b-button>
          </b-col>
        </b-row>
      </b-col>

      <b-col cols="12" class="mt-auto">
        <slot />
      </b-col>
    </b-row>
  </div>
</template>

<script>
import moment from 'moment'
import { mapGetters, mapActions } from 'vuex'
import phoneMixin from '@/app/_global/mixins/phoneMixin'

let CountdownInterval = undefined

export default {
  name: 'EWalletOtpVerificationForm',
  $_veeValidate: {
    validator: 'new',
  },
  mixins: [phoneMixin],
  props: {
    dataQaPrefix: { type: String, required: true },
    mobileObject: { type: Object, required: true },
    activation: { type: Boolean, default: false },
    requestVerification: { type: Boolean, default: false },
  },
  data() {
    return {
      customError: '',
      fieldsLock: false,
      resendCountdown: 0,
      verificationCode: '',
    }
  },
  watch: {
    verificationCode() {
      this.customError = ''
      this.$validator.reset()
    },
  },
  computed: {
    ...mapGetters(['getErrors']),
    getMaskedMobileNumber() {
      let { countryCode: code, phoneNumber: number } = this.mobileObject
      return this.phoneNumberMasking(code, number)
    },
    getCountdownTime() {
      return moment.duration(this.resendCountdown, 'seconds').format('mm:ss')
    },
  },
  mounted() {
    this.requestVerification && this.requestVerificationCode()
  },
  activated() {
    !this.requestVerification && this.initResendCountdown()
  },
  deactivated() {
    this.dismissResendCountdown()
    this.$nextTick(() => {
      this.verificationCode = ''
      this.$validator.reset()
    })
  },
  methods: {
    ...mapActions(['requestEWalletVerificationCode', 'validateEWalletVerificationCode']),
    async validateAndSubmit() {
      let self = this
      let { countryCode, phoneNumber } = { ...self.mobileObject }
      if (countryCode && phoneNumber) {
        self.fieldsLock = true

        return await self.$validator.validate().then(async valid => {
          let result = valid

          if (result) {
            let payload = {
              ...self.mobileObject,
              verificationCode: self.verificationCode,
              activation: self.activation,
            }

            await self.validateEWalletVerificationCode(payload).then(res => {
              if (!res) {
                self.customError =
                  self.getErrors('eWalletVerificationCodeValidation') || self.$t('Common.UnexpectedErrorHeader.Msg')
                result = false
              }
            })
          }

          self.fieldsLock = false
          return result
        })
      } else {
        await self.$swal({
          type: 'error',
          title: this.$t('Common.Error.IncompletePhoneNumber'),
        })
      }
    },
    async requestVerificationCode() {
      let self = this
      let { countryCode, phoneNumber } = { ...this.mobileObject }
      if (countryCode && phoneNumber) {
        if (this.resendCountdown === 0) {
          this.verificationCode = ''
          this.initResendCountdown()
          await this.requestEWalletVerificationCode(self.mobileObject).then(res => {
            if (!res) {
              self.dismissResendCountdown()
              self.$swal({
                type: 'error',
                title: self.$t('Common.Error.VerificationCodeRequestFailed'),
                text:
                  self.getErrors('eWalletVerificationCodeRequest') || self.$t('Common.Error.ActionFailure.HelpText'),
              })
            }
          })
        }
      } else {
        this.dismissResendCountdown()
        await this.$swal({
          type: 'error',
          title: this.$t('Common.Error.VerificationCodeRequestFailed'),
          text: this.$t('Common.Error.IncompletePhoneNumber'),
        })
      }
    },
    initResendCountdown() {
      this.resendCountdown = 5 * 60 // minute * seconds
      CountdownInterval = setInterval(() => {
        this.resendCountdown < 1 ? clearInterval(CountdownInterval) : this.resendCountdown--
      }, 1000)
    },
    dismissResendCountdown() {
      clearInterval(CountdownInterval)
      this.resendCountdown = 0
    },
  },
}
</script>
