<template>
  <b-row>
    <b-col md="8" lg="7" xl="5" class="mb-5">
      <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')">
        <b-form-input id="RecipientEmail" readonly :value="getFundWithdrawalDetails.recipientEmail" class="rounded-1" />
      </b-form-group>

      <b-form-group label-for="RecipientReference" :label="$t('EWallet.TransactionForm.RecipientReference')">
        <b-form-textarea
          id="RecipientReference"
          rows="3"
          readonly
          no-resize
          class="rounded-1"
          :value="getFundWithdrawalDetails.recipientReference"
        />
      </b-form-group>

      <b-form-group
        class="mb-0"
        label-for="SecurityPin"
        :label-class="['required']"
        :label="$t('Common.Security.SecurityPin')"
        :invalid-feedback="errors.first('Security Pin')"
      >
        <b-form-input
          id="SecurityPin"
          lazy
          maxlength="6"
          type="password"
          name="Security Pin"
          v-model="securityPin"
          :disabled="fieldLock"
          class="rounded-1 col-6 col-md-4"
          v-validate="'required|digits:6'"
          :state="!errors.has('Security Pin') && null"
          :data-vv-as="$t('Common.Security.SecurityPin')"
          :data-qa="`${dataQaPrefix}-fundWithdrawalConfirmation-securityPin-input`"
        />
      </b-form-group>
      <b-button variant="link" class="px-0" :disabled="fieldLock" @click="openResetSecurityPinModal()">
        {{ $t('Common.Security.ForgotSecurityPin') }}
      </b-button>
    </b-col>

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

    <e-wallet-reset-security-pin-modal
      v-if="showResetPinModal"
      @close="closeModal"
      :phone-number-details="getMemberContactInfo"
      :data-qa-prefix="`${dataQaPrefix}-fundWithdrawalConfirmation`"
      ref="resetSecurityPinModal"
    />
  </b-row>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'
import { mapMasterDataId } from '@/app/_global/mixins'
import eWalletResetPinModalMixin from '@/app/ewallet/_global/components/Mixins/eWalletResetPinModalMixin'
import EWalletResetSecurityPinModal from '@/app/ewallet/_global/components/blocks/EWalletResetSecurityPinModal'

export default {
  name: 'FundWithdrawalConfirmationForm',
  mixins: [eWalletResetPinModalMixin],
  $_veeValidate: {
    validator: 'new',
  },
  components: { EWalletResetSecurityPinModal },
  props: {
    dataQaPrefix: { type: String, required: true },
    fundWithdrawalDetails: { type: Object, required: true },
  },
  data() {
    return {
      securityPin: '',
      fieldLock: false,
      transactionReceipt: {},
    }
  },
  computed: {
    ...mapMasterDataId({
      ewallet_transaction_type: {
        fundWithdrawTransactionId: 'Withdraw',
      },
    }),
    ...mapGetters(['getErrors']),
    getFundWithdrawalDetails() {
      let { fromIbo, fromName, recipientEmail, recipientReference, bankMeta } = this.fundWithdrawalDetails
      return {
        recipientEmail,
        recipientReference,
        bankMeta: { ...bankMeta },
        fromIbo: `${fromIbo || ''} ${fromName || ''}`,
      }
    },
  },
  deactivated() {
    this.$nextTick(() => {
      this.securityPin = ''
      this.$validator.reset()
    })
  },
  methods: {
    ...mapActions(['createEWalletTransaction']),
    async validateAndSubmit() {
      let self = this
      self.fieldLock = true
      return await self.$validator.validate().then(async valid => {
        let result = valid

        if (result) {
          await self.resolveMasters
          let payload = {
            securityPin: self.securityPin,
            amount: self.fundWithdrawalDetails.amount,
            transactionTypeId: self.fundWithdrawTransactionId,
            recipientEmail: self.fundWithdrawalDetails.recipientEmail,
            recipientReference: self.fundWithdrawalDetails.recipientReference,
          }
          await self.createEWalletTransaction(payload).then(res => {
            if (res) {
              let {
                id,
                amount,
                after_balance,
                recipient_email,
                transaction_date,
                transaction_number,
                recipient_reference,
                member_payment_info,
                transaction_status: { key: transaction_key },
              } = res

              this.transactionReceipt = {
                id,
                amount: amount,
                eWalletBalance: after_balance,
                recipientEmail: recipient_email,
                transactionStatus: transaction_key,
                transactionNumber: transaction_number,
                transactionDateTime: transaction_date,
                recipientReference: recipient_reference,
                bankMeta: self.fetchBankDetails(member_payment_info),
              }
            } else {
              self.$swal({
                type: 'error',
                title: self.$t('EWallet.Transaction.CreateTransaction.Fail'),
                text: self.getErrors('createEWalletTransaction'),
              })
              result = false
            }
          })
        } else {
          self.$swal({
            type: 'error',
            title: self.errors.items[0].msg || '',
            timer: '2300',
          })
        }

        self.fieldLock = false
        return result
      })
    },
    getComponentModelData() {
      return this.transactionReceipt
    },
    fetchBankDetails(source) {
      try {
        return JSON.parse(source)
      } catch {
        return {}
      }
    },
  },
}
</script>
