<template>
  <div class="product-quantity" :class="{ 'inline no-wrap': !simple }" :key="`product-cart-${productId}-${kittingId}`">
    <div class="advance" v-if="!simple">
      <b-button
        variant="link"
        @click="removeQuantity()"
        :data-qa="`${$helpers.kebabCase(dataQaPrefix)}-product-minus-btn`"
      >
        <icon name="eshop-minus" />
      </b-button>
      <div
        :class="{
          'quantity-input': true,
          'is-adding': isAdding,
          'float-left': variant === 'side',
          'mr-2': variant === 'side',
        }"
      >
        <b-form-input
          class="no-spin"
          type="number"
          :value="currentQuantity"
          @change="changeQuantity"
          :max="max"
          :disabled="disableField()"
          :data-qa="`${$helpers.kebabCase(dataQaPrefix)}-quantity-field`"
        />
      </div>
      <b-button
        variant="link"
        @click="addQuantity"
        :disabled="disableField()"
        :data-qa="`${$helpers.kebabCase(dataQaPrefix)}-plus-btn`"
      >
        <icon name="eshop-plus" />
      </b-button>
    </div>
    <div :class="{ 'col-6': shortBtn, simple: true }" v-else>
      <b-button
        block
        :variant="productViewingMode ? 'primary' : 'outline-primary'"
        @click="addQuantity"
        :disabled="btnLock"
        v-if="productQuantityGetter(productId, kittingId) === 0 && salesTypeId === rentalSalesTypeId"
        :data-qa="`${$helpers.kebabCase(dataQaPrefix)}-subscribe-btn`"
      >
        <b-spinner small v-if="isAdding" class="mr-2"></b-spinner>
        <span>{{ $t('Enrolment.Subscribe.Label') }}</span>
      </b-button>
      <b-button
        block
        variant="outline-primary"
        @click="addQuantity"
        v-if="productQuantityGetter(productId, kittingId) === 0 && salesTypeId !== rentalSalesTypeId"
        :data-qa="`${$helpers.kebabCase(dataQaPrefix)}-buy-btn`"
      >
        {{ $t('Enrolment.Buy.Label') }}
      </b-button>
      <b-button
        v-if="productQuantityGetter(productId, kittingId) > 0 && salesTypeId === rentalSalesTypeId"
        class="w-100 remove-btn"
        variant="outline-primary"
        @click="removeQuantity(productQuantityGetter(productId, kittingId))"
        :data-qa="`${$helpers.kebabCase(dataQaPrefix)}-remove-btn`"
      >
        <b-spinner small v-if="isAdding" class="mr-2"></b-spinner>
        <span>{{ $t('Enrolment.Remove.Label') }}</span>
      </b-button>
      <b-button-group
        class="d-flex"
        v-if="productQuantityGetter(productId, kittingId) > 0 && salesTypeId !== rentalSalesTypeId"
      >
        <b-button
          class="w-50 remove-btn"
          variant="outline-primary"
          @click="removeQuantity(productQuantityGetter(productId, kittingId))"
          :data-qa="`${$helpers.kebabCase(dataQaPrefix)}-remove-btn`"
        >
          {{ $t('Enrolment.Remove.Label') }}
        </b-button>
        <b-button
          class="w-50"
          variant="outline-primary"
          @click="addQuantity"
          :data-qa="`${$helpers.kebabCase(dataQaPrefix)}-add-btn`"
        >
          {{ $t('Enrolment.Add.Label') }}
        </b-button>
      </b-button-group>
    </div>
  </div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
import { mapMasterDataId } from '@/app/_global/mixins'

export default {
  name: 'EshopCartBtn',
  props: [
    'quantity',
    'productId',
    'kittingId',
    'salesTypeId',
    'focQty',
    'processCartCallback',
    'isAdding',
    'variant',
    'max',
    'simple',
    'productQuantityGetter',
    'shortBtn',
    'productViewingMode',
    'dataQaPrefix',
    'getCustomProductDetails',
    'customProductDetails',
  ],
  data() {
    return {
      initQuantity: false,
      hideAddRemoveBtn: false,
      isRental: false,
      btnLock: false,
    }
  },
  methods: {
    addQuantity() {
      this.btnLock = true
      let newQuantity = 0
      if (this.initQuantity === false) {
        newQuantity = this.$props.quantity + 1
      } else {
        newQuantity = this.initQuantity + 1
      }
      if (typeof this.max === 'undefined' || newQuantity <= this.max) {
        this.initQuantity = newQuantity
      }
    },
    removeQuantity(qty) {
      let newQuantity = 0
      let minusQuantity = qty !== undefined ? qty : 1
      if (this.initQuantity === false) {
        newQuantity = this.$props.quantity - minusQuantity
      } else {
        newQuantity = this.initQuantity - minusQuantity
      }
      this.initQuantity = newQuantity > 0 ? newQuantity : 0
    },
    refresh() {
      this.initQuantity = false
    },
    changeQuantity(value) {
      if (typeof this.max === 'undefined') {
        this.initQuantity = parseInt(value)
      } else if (value <= this.max) {
        this.initQuantity = parseInt(value)
      } else if (value > this.max) {
        this.initQuantity = parseInt(this.max)
      }
      if (isNaN(this.initQuantity)) {
        this.initQuantity = 0
      }
    },
    disableField() {
      let setDisabled = false
      if (this.salesTypeId !== undefined) {
        if (this.salesTypeId === this.rentalSalesTypeId && this.getCartTotal > 0) {
          setDisabled = true
        }
      }
      return setDisabled
    },
    appendCustomProductDetails() {
      return this.getCustomProductDetails === true ? { custom: { ...this.customProductDetails } } : {}
    },
  },
  computed: {
    currentQuantity() {
      return this.initQuantity !== false ? this.initQuantity : this.quantity
    },
    ...mapGetters(['getMasterDataTitleByKeyAndId']),
    ...mapGetters('eshop', ['getCartHasRentalProducts', 'getCartTotal', 'getCartProductQuantity']),
    ...mapMasterDataId({
      SALE_TYPES: {
        rentalSalesTypeId: 'RENTAL',
      },
    }),
  },
  watch: {
    initQuantity() {
      let self = this
      if (this.initQuantity !== false && this.processCartCallback !== undefined) {
        // this.processCartCallback might not return a promise, so we wrap it with Promise.resolve
        Promise.resolve(
          this.processCartCallback({
            product_id: this.productId,
            kitting_id: this.kittingId,
            quantity: this.initQuantity,
            foc_qty: this.focQty,
            salesTypeId: this.salesTypeId,
            ...this.appendCustomProductDetails(),
          })
        ).then(result => {
          self.$emit('product-quantity-update')
          if (result === false) {
            self.initQuantity = false
            self.btnLock = false
          }
        })
      }
    },
    quantity() {
      if (this.initQuantity !== false) {
        if (this.quantity === this.initQuantity) {
          this.initQuantity = false
        } else if (this.processCartCallback !== undefined) {
          this.processCartCallback({
            product_id: this.productId,
            kitting_id: this.kittingId,
            quantity: this.initQuantity,
            foc_qty: this.focQty,
            salesTypeId: this.salesTypeId,
            ...this.appendCustomProductDetails(),
          })
        }
      }
    },
    productViewingMode(val) {
      return typeof val === 'boolean' && val
    },
    getCartTotal() {
      if (
        this.btnLock &&
        this.salesTypeId === this.rentalSalesTypeId &&
        this.getCartProductQuantity(this.productId, this.kittingId) === 0
      ) {
        this.btnLock = false
      }
    },
  },
}
</script>
