<template>
  <div>
    <b-button
      v-if="!forceShowQuantitySelector && productQuantity === 0"
      block
      variant="primary"
      :disabled="isBusy || disabled"
      @click="() => (productQuantity = 1)"
      class="text-uppercase d-flex align-items-center justify-content-center animated fadeIn py-2"
      :data-qa="`${dataQaPrefix}-eshopProductQuantitySelector-${(isRental && 'subscribe') || 'addToCart'}-btn`"
    >
      <span>{{ addToCartBtnText || $t((isRental && 'Enrolment.Subscribe.Label') || 'Eshop.AddToCart.Label') }}</span>
      <b-spinner v-show="isBusy" small class="ml-2" />
    </b-button>

    <div v-else class="animated fadeIn">
      <b-button
        v-if="!forceShowQuantitySelector && (isRental || maxRange === 1)"
        block
        :disabled="isBusy || disabled"
        variant="outline-medium"
        @click="() => (productQuantity = 0)"
        class="text-uppercase d-flex align-items-center justify-content-center py-2"
        :data-qa="`${dataQaPrefix}-eshopProductQuantitySelector-remove-btn`"
      >
        <span>{{ $t('Enrolment.Remove.Label') }}</span>
        <b-spinner v-show="isBusy" small class="ml-2" />
      </b-button>

      <quantity-selector
        v-else
        :pill="pill"
        :min-range="0"
        :is-busy="isBusy"
        :max-range="maxRange"
        v-model="productQuantity"
        :small="smallQuantitySelector"
        :linear-quantity-increment="false"
        :class="{ 'justify-content-center': centered }"
        :quantity-buttons-wrapper-class="quantityButtonsWrapperClass"
        :data-qa-prefix="`${dataQaPrefix}-eshopProductQuantitySelector`"
      />
    </div>
  </div>
</template>

<script>
import QuantitySelector from '@/app/_global/components/blocks/QuantitySelector'
export default {
  name: 'EshopProductQuantitySelector',
  components: { QuantitySelector },
  props: {
    disabled: { type: Boolean, default: false },
    addToCartBtnText: { type: String },
    dataQaPrefix: { type: String, required: true },
    quantity: { type: Number, default: 0 },
    centered: { type: Boolean, default: false },
    isRental: { type: Boolean, default: false },
    pill: { type: Boolean, default: false },
    isBusy: { type: Boolean, default: false },
    maxRange: { type: Number, default: 999 },
    smallQuantitySelector: { type: Boolean, default: false },
    forceShowQuantitySelector: { type: Boolean, default: false },
    quantityButtonsWrapperClass: { type: [Array, String], default: () => [] },
  },
  data() {
    return {
      productQuantity: 0,
    }
  },
  watch: {
    quantity: {
      handler(val) {
        if (val !== this.productQuantity) {
          this.setProductQuantity(val)
        }
      },
      immediate: true,
    },
    productQuantity(val) {
      if (val !== this.quantity) {
        this.$emit('update', val)
      }
    },
  },
  methods: {
    setProductQuantity(qty = 0) {
      this.productQuantity = qty
    },
  },
}
</script>
