<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 :value="getFundTransferDetails.fromIbo" class="rounded-1 text-uppercase" />
      </b-form-group>

      <b-form-group label-for="ToIbo" :label="$t('EWallet.FundTransfer.ToIboId')">
        <b-form-input id="ToIbo" readonly :value="getFundTransferDetails.toIbo" class="rounded-1 text-uppercase" />
      </b-form-group>

      <b-form-group label-for="RecipientEmail" :label="$t('EWallet.TransactionForm.RecipientEmail')">
        <b-form-input id="RecipientEmail" readonly :value="getFundTransferDetails.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="getFundTransferDetails.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}-fundTransferConfirmation-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}-fundTransferConfirmation`"
      ref="resetSecurityPinModal"
    />
  </b-row>
</template>

<script>
import { mapGetters, mapActions } 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: 'FundTransferConfirmationForm',
  mixins: [eWalletResetPinModalMixin],
  $_veeValidate: {
    validator: 'new',
  },
  components: { EWalletResetSecurityPinModal },
  props: {
    dataQaPrefix: { type: String, required: true },
    fundTransferDetails: { type: Object, required: true },
  },
  data() {
    return {
      securityPin: '',
      fieldLock: false,
      transactionReceipt: {},
    }
  },
  computed: {
    ...mapMasterDataId({
      ewallet_transaction_type: {
        fundTransferTransactionId: 'Transfer',
      },
    }),
    ...mapGetters(['getErrors']),
    getFundTransferDetails() {
      let { fromIbo, fromName, targetIbo, targetName, recipientEmail, recipientReference } = this.fundTransferDetails
      return {
        recipientEmail,
        recipientReference,
        fromIbo: `${fromIbo || ''} ${fromName || ''}`,
        toIbo: `${targetIbo || ''} ${targetName || ''}`,
      }
    },
  },
  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.fundTransferDetails.amount,
            transactionTypeId: self.fundTransferTransactionId,
            recipientEmail: self.fundTransferDetails.recipientEmail,
            transferToUserId: self.fundTransferDetails.targetUserId,
            recipientReference: self.fundTransferDetails.recipientReference,
          }
          await self.createEWalletTransaction(payload).then(res => {
            if (res) {
              let {
                id,
                amount,
                transaction_date,
                transaction_number,
                recipient_reference,
                transfer_to_user: { name, old_member_id },
                transaction_status: { key: transaction_key },
              } = res

              this.transactionReceipt = {
                id,
                amount,
                targetName: name,
                targetIbo: old_member_id,
                transactionStatus: transaction_key,
                transactionNumber: transaction_number,
                transactionDateTime: transaction_date,
                recipientReference: recipient_reference,
              }
            } else {
              this.$swal({
                type: 'error',
                title: this.$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
    },
  },
}
</script>
