<template>
  <b-row>
    <b-col md="8" lg="7" xl="5" class="mb-5">
      <b-form-group
        label-for="Amount"
        :label-class="['required']"
        :label="$t('EWallet.Amount')"
        :invalid-feedback="customError.amount || errors.first('Amount')"
      >
        <b-form-input
          id="Amount"
          type="number"
          name="Amount"
          placeholder="0.00"
          :disabled="fieldLock"
          v-model="formData.amount"
          class="rounded-1 col-6 col-lg-5"
          :data-vv-as="$t('EWallet.Amount')"
          :state="!(customError.amount || errors.has('Amount')) && null"
          v-validate="`required|between:${minTransactionLimit},999999.99|max:9`"
          :data-qa="`${dataQaPrefix}-fundWithdrawal-amount-input`"
        />
      </b-form-group>

      <b-form-group label-for="FromIbo" :label="$t('EWallet.TransactionForm.FromIboId')">
        <b-form-input
          id="FromIbo"
          readonly
          class="rounded-1 text-uppercase"
          :value="getFundWithdrawalDetails.fromIbo"
        />
      </b-form-group>

      <b-form-group
        v-for="(field, index) in getFundWithdrawalDetails.bankMeta"
        :key="index"
        :label="field.label"
        :label-for="`BankInfoField${index}`"
      >
        <b-form-input :id="`BankInfoField${index}`" readonly :value="field.value" class="rounded-1" />
      </b-form-group>

      <b-form-group
        label-for="RecipientEmail"
        :label="$t('EWallet.TransactionForm.RecipientEmail')"
        :invalid-feedback="errors.first('Recipient Email')"
      >
        <b-form-input
          id="RecipientEmail"
          lazy
          type="email"
          class="rounded-1"
          v-validate="'email'"
          :disabled="fieldLock"
          name="Recipient Email"
          v-model="formData.recipientEmail"
          placeholder="emailaddress@elken.com"
          :state="!errors.has('Recipient Email') && null"
          :data-vv-as="$t('EWallet.TransactionForm.RecipientEmail')"
          :data-qa="`${dataQaPrefix}-fundWithdrawal-recipientEmail-input`"
        />
      </b-form-group>

      <b-form-group
        label-for="RecipientReference"
        :label="$t('EWallet.TransactionForm.RecipientReference')"
        :invalid-feedback="errors.first('Recipient Reference')"
      >
        <!-- Purposely set maxlength = upper limit + 1 to display error -->
        <b-form-textarea
          id="RecipientReference"
          trim
          rows="3"
          no-resize
          maxlength="121"
          class="rounded-1"
          :disabled="fieldLock"
          v-validate="'max:120'"
          name="Recipient Reference"
          v-model="formData.recipientReference"
          :state="!errors.has('Recipient Reference') && null"
          :data-vv-as="$t('EWallet.TransactionForm.RecipientReference')"
          :placeholder="$t('EWallet.TransactionForm.Placeholder.Optional')"
          :data-qa="`${dataQaPrefix}-fundWithdrawal-recipientReference-input`"
        />
      </b-form-group>
    </b-col>

    <b-col cols="12">
      <slot />
    </b-col>
  </b-row>
</template>

<script>
import { mapGetters } from 'vuex'
import { convertToCurrencyAmount } from '@/helpers/currency-formatter'

export default {
  name: 'FundWithdrawalForm',
  $_veeValidate: {
    validator: 'new',
  },
  props: {
    dataQaPrefix: { type: String, required: true },
    minTransactionLimit: { type: String, default: '0.01' },
    fundWithdrawalDetails: { type: Object, required: true },
  },
  data() {
    return {
      fieldLock: false,
      formData: {
        amount: null,
        recipientEmail: '',
        recipientReference: '',
      },
      customError: {
        amount: '',
      },
    }
  },
  watch: {
    'formData.amount'() {
      this.customError.amount = ''
    },
  },
  computed: {
    ...mapGetters(['getEWalletDetails']),
    getFundWithdrawalDetails() {
      let { fromIbo, fromName, bankMeta } = this.fundWithdrawalDetails
      return {
        bankMeta: { ...bankMeta },
        fromIbo: `${fromIbo || ''} ${fromName || ''}`,
      }
    },
  },
  methods: {
    async validateAndSubmit() {
      let self = this
      self.fieldLock = true

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

        if (result) {
          /** Note: below currency (decimal point) conversion max support until 13 CHAR long number ONLY
           * as it will cause DECIMAL_POINT_CONVERSION_ERROR by computer
           * e.g. : 9.99999999999 * 100 will equals to 999.9999999990001
           * e.g. : 9.999999999999999 *100 will equals to 999.9999999999998
           * e.g. : 9.9999999999999999 *100 will equals to 1000
           */
          let transactionAmount = Math.floor(self.formData.amount * 100)
          let currentBalance = Math.floor((self.getEWalletDetails.balance || '0') * 100)

          if (transactionAmount <= currentBalance) {
            self.formData.amount = convertToCurrencyAmount(self.formData.amount)
          } else {
            self.customError.amount = self.$t('EWallet.Transaction.InsufficientFund')
            result = false
          }
        } else {
          self.$swal({
            type: 'error',
            title: self.errors.items[0].msg || '',
            timer: '2300',
          })
        }

        self.fieldLock = false
        return result
      })
    },
    getComponentModelData() {
      return this.formData
    },
  },
}
</script>
