<template>
  <div class="dashboard-panel-element rounded-0 p-0" v-can:view="'e-wallet'">
    <e-wallet-transaction-template
      class="pb-4"
      :e-wallet-balance="getEWalletBalance"
      :current-step="getCurrentStepMeta.step"
      :total-steps="fundWithdrawalSteps.length"
      :is-busy="isLoading('loadingEWalletDetails')"
      :transaction-amount="fundWithdrawalFormData.amount"
      :steps-description="getCurrentStepMeta.stepDescription"
      :transaction-title="getCurrentStepMeta.transactionTitle"
      :show-e-wallet-balance="getCurrentStepMeta.showEWalletBalance"
      :show-transaction-banner="getCurrentStepMeta.showTransactionBanner"
      :transaction-description="getCurrentStepMeta.transactionDescription"
    >
      <keep-alive :max="2">
        <component :is="getCurrentStepMeta.component" v-bind="getCurrentStepMeta.bind" :ref="getCurrentStepMeta.ref">
          <div class="d-flex">
            <b-button
              v-if="getCurrentStepMeta.showBackBtn"
              size="lg"
              @click="backAction"
              variant="outline-primary"
              class="mr-3 px-4 px-md-5"
              :data-qa="`${dataQaPrefix}-${(currentStep === 1 && 'cancel') || 'back'}-btn`"
            >
              <span>{{ $t((currentStep === 1 && 'Common.Cancel') || 'Common.Back') }}</span>
            </b-button>
            <b-button
              v-if="getCurrentStepMeta.showNextBtn"
              size="lg"
              variant="primary"
              @click="nextAction"
              :disabled="getLoadingStatus"
              class="d-flex align-items-center px-4 px-md-5"
              :data-qa="`${dataQaPrefix}-${(getCurrentStepMeta.isSubmit && 'confirm') || 'continue'}-btn`"
            >
              <span>{{ $t((getCurrentStepMeta.isSubmit && 'Common.Confirm') || 'Common.Continue') }}</span>
              <b-spinner v-show="getLoadingStatus" small class="ml-2" />
            </b-button>
          </div>
        </component>
      </keep-alive>
    </e-wallet-transaction-template>
  </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'
import { getValue } from '@/helpers/variable-handling'
import eWalletCommonMixin from '@/app/ewallet/_global/components/Mixins/eWalletCommonMixin'
import eWalletBankDetailsMixin from '@/app/ewallet/_global/components/Mixins/eWalletBankDetailsMixin'
import EWalletTransactionTemplate from '@/app/ewallet/_global/components/template/EWalletTransactionTemplate'

export default {
  name: 'EWalletFundWithdrawalWrapper',
  mixins: [eWalletCommonMixin, eWalletBankDetailsMixin],
  components: { EWalletTransactionTemplate },
  data() {
    return {
      minTransactionLimit: '0.01',
      fundWithdrawalFormData: {},
      currentStep: 1,
      fundWithdrawalSteps: [
        {
          step: 1,
          showBackBtn: true,
          showNextBtn: true,
          showEWalletBalance: true,
          showTransactionBanner: false,
          transactionTitle: this.$t('EWallet.FundWithdrawal'),
          component: () => import('@/app/ewallet/fund-withdrawal/blocks/FundWithdrawalForm'),
          stepDescription: this.$t('EWallet.FundWithdrawal.ApplicationFormStepDescription'),
          ref: 'fundWithdrawalForm',
        },
        {
          step: 2,
          isSubmit: true,
          showBackBtn: true,
          showNextBtn: true,
          showEWalletBalance: true,
          showTransactionBanner: true,
          transactionTitle: this.$t('EWallet.FundWithdrawal'),
          transactionDescription: this.$t('EWallet.FundWithdrawal.AmountToWithdrawn'),
          stepDescription: this.$t('EWallet.FundWithdrawal.ConfirmationFormStepDescription'),
          component: () => import('@/app/ewallet/fund-withdrawal/blocks/FundWithdrawalConfirmationForm'),
          ref: 'confirmationForm',
        },
        {
          step: 3,
          showEWalletBalance: false,
          showTransactionBanner: true,
          transactionTitle: this.$t('EWallet.FundWithdrawal.Status.RequestSubmitted'),
          transactionDescription: this.$t('EWallet.FundWithdrawal.AmountWithdrew'),
          component: () => import('@/app/ewallet/fund-withdrawal/blocks/FundWithdrawalReceiptForm'),
          ref: 'receiptForm',
        },
      ],
      dataQaPrefix: 'eWallet-eWalletFundWithdrawal',
    }
  },
  watch: {
    currentStep() {
      this.$scrollTo('body')
    },
  },
  computed: {
    ...mapGetters(['isLoading', 'getMyAccountMemberDetails']),
    getCurrentStepMeta() {
      let component = this.fundWithdrawalSteps.find(el => el.step === this.currentStep) || {}
      component = this.propsBindingFactory(component)
      return component
    },
    getLoadingStatus() {
      let loaders = ['creatingEWalletTransaction']
      return this.isLoading(loaders)
    },
  },
  async mounted() {
    await this.initMixin().then(() => {
      if (this.requiredBankAccountSetup) {
        let query = {}
        query[(this.isBankInfoExpired && 'expired') || 'missing'] = 1
        this.$router.replace({ name: 'EWalletHome', query })
      }
    })
    await this.loadBackendSetting(['bonus_payout_settings']).then(res => {
      let memberCountry = getValue(this.getMyAccountMemberDetails, 'details.country.code_iso_2')
      let countriesLimit = getValue(res, 'bonus_payout_settings.data', {})
      this.minTransactionLimit = (
        (countriesLimit[memberCountry] && countriesLimit[memberCountry].min_amount) ||
        '0.01'
      ).toString()
    })
  },
  methods: {
    ...mapActions(['loadBackendSetting']),
    async nextAction() {
      let self = this
      let currentStep = this.getCurrentStepMeta

      if (currentStep.ref) {
        await this.$refs[currentStep.ref].validateAndSubmit().then(res => {
          if (res) {
            self.setFormData(currentStep.ref)
            if (self.currentStep < self.fundWithdrawalSteps.length) {
              self.currentStep++
            }
          }
        })
      }
    },
    backAction() {
      if (this.currentStep <= 1) {
        this.$router.push({ name: 'EWalletHome' })
      } else {
        this.currentStep = this.currentStep - 1
      }
    },
    propsBindingFactory(details) {
      let dataQaPrefix = this.dataQaPrefix
      let { member_id, name } = this.getMyAccountMemberDetails.details
      let rawMemberBankDynamicContent = getValue(this.getMyAccountMemberDetails, 'banking.payment_data', {})

      if (details.ref === 'fundWithdrawalForm') {
        details['bind'] = {
          dataQaPrefix,
          minTransactionLimit: this.minTransactionLimit,
          fundWithdrawalDetails: {
            fromName: name,
            fromIbo: member_id,
            bankMeta: this.getBankDetails(rawMemberBankDynamicContent),
          },
        }
      } else if (details.ref === 'confirmationForm') {
        details['bind'] = {
          dataQaPrefix,
          fundWithdrawalDetails: {
            fromName: name,
            fromIbo: member_id,
            bankMeta: this.getBankDetails(rawMemberBankDynamicContent),
            ...this.fundWithdrawalFormData,
          },
        }
      } else if (details.ref === 'receiptForm') {
        details['bind'] = {
          dataQaPrefix,
          receiptDetails: {
            fromName: name,
            fromIbo: member_id,
            ...this.fundWithdrawalFormData,
            bankMeta: this.getBankDetails(this.fundWithdrawalFormData.bankMeta),
          },
        }
      }

      return details
    },
    setFormData(key) {
      if (key === 'fundWithdrawalForm' || key === 'confirmationForm') {
        this.fundWithdrawalFormData = { ...this.$refs[key].getComponentModelData() }
      }
    },
  },
}
</script>
