<template>
  <div>
    <b-checkbox
      v-if="showRedeemLaterOption"
      class="text-right mb-4"
      :checked="getRedeemLaterStatus"
      @change="updateITokenRedeemLaterStatus(!getRedeemLaterStatus)"
    >
      {{ $t('Eshop.IToken.RedeemLater') }}
    </b-checkbox>

    <i-token-voucher-details
      :voucher-details="getVoucherDetails"
      :show-quantity-selector="!getRedeemLaterStatus"
      :total-redeemed-points="getTotalPointsRedeemed"
      :add-to-cart-call-back="addITokenRedemptionProduct"
      :product-quantity-getter="getITokenCartProductUnitQuantity"
      data-qa-prefix="eshop-iToken-selectRedemption"
    />
  </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'
import currencyMixin from '@/app/_global/mixins/currencyMixin'
import ITokenVoucherDetails from '@/app/i-token/_global/components/blocks/ITokenVoucherDetails'

export default {
  name: 'SelectRedemption',
  mixins: [currencyMixin],
  components: { ITokenVoucherDetails },
  data() {
    return {
      voucherDetails: {},
    }
  },
  computed: {
    ...mapGetters(['isLoading']),
    ...mapGetters('eshop', [
      'getITokenCartProductUnitQuantity',
      'getCartCampaignDetails',
      'getITokenCartItems',
      'getRedeemLaterStatus',
    ]),
    getVoucherDetails() {
      let { id, name, calculation, items } = this.getCartCampaignDetails || {}
      return {
        id,
        campaign_name: name || '',
        voucher_points: (calculation && calculation.total_point) || 0,
        items: items || [],
        currency_code: this.currency,
      }
    },
    showRedeemLaterOption() {
      return this.$helpers.getValue(this.getCartCampaignDetails, 'redemption_method.key') === 'both'
    },
    getTotalPointsRedeemed() {
      return this.getITokenCartItems.reduce((accumulate, current) => {
        return accumulate + current.quantity * current.unit_point
      }, 0)
    },
  },
  methods: {
    ...mapActions('eshop', [
      'addITokenRedemptionProduct',
      'updateITokenRedemptionCart',
      'updateITokenRedeemLaterStatus',
    ]),
    async preCheckout(next) {
      let error = {}

      if (this.getVoucherDetails.voucher_points < this.getTotalPointsRedeemed) {
        error = {
          title: this.$t('Itoken.Redemption.Error.InSufficientPoints'),
          text: this.$t('Itoken.Redemption.Error.InSufficientPoints.HelpText'),
        }
      } else if (this.showRedeemLaterOption && this.getITokenCartItems.length < 1 && !this.getRedeemLaterStatus) {
        error = { type: 'warning', title: this.$t('Itoken.Redemption.Error.AccumulationNotice') }
      }

      if (error.title) {
        this.$swal({ type: 'error', ...error })
      } else {
        if (this.getRedeemLaterStatus) {
          this.updateITokenRedemptionCart([])
        }
        next()
      }
    },
  },
}
</script>
