<template>
  <b-row class="align-items-baseline custom-quantity-selector">
    <b-col cols="auto" :class="quantityButtonsWrapperClass">
      <b-button
        variant="white"
        :disabled="min"
        @click="decrement"
        class="p-0 rounded-circle border-0"
        :data-qa="`${dataQaPrefix}-quantitySelector-minus-btn`"
      >
        <b-icon icon="dash-circle" font-scale="1.5" :variant="min ? 'light' : 'primary'" />
      </b-button>
    </b-col>
    <b-col cols="auto" class="px-0">
      <b-form-input
        lazy
        number
        size="sm"
        type="number"
        :min="minRange"
        :max="maxRange"
        v-model="quantity"
        :formatter="quantityFormatter"
        class="text-center bg-white quantity-input"
        :disabled="linearQuantityIncrement || isBusy"
        :class="[{ 'rounded-0': squared }, { 'rounded-pill': pill }, { loading: isBusy }, { 'p-0': small }]"
        :data-qa="`${dataQaPrefix}-quantitySelector-quantity-input`"
      />
    </b-col>

    <b-col cols="auto" :class="quantityButtonsWrapperClass">
      <b-button
        variant="white"
        :disabled="max"
        @click="increment"
        class="p-0 rounded-circle border-0"
        :data-qa="`${dataQaPrefix}-quantitySelector-plus-btn`"
      >
        <b-icon icon="plus-circle" font-scale="1.5" :variant="max ? 'light' : 'primary'" />
      </b-button>
    </b-col>
  </b-row>
</template>

<script>
export default {
  name: 'QuantitySelector',
  props: {
    small: { type: Boolean, default: false },
    dataQaPrefix: { type: String, required: true },
    value: { type: [Number, String], default: 1 },
    minRange: { type: Number, default: 1 },
    maxRange: { type: Number, default: 100 },
    pill: { type: Boolean, default: false },
    isBusy: { type: Boolean, default: false },
    squared: { type: Boolean, default: false },
    linearQuantityIncrement: { type: Boolean, default: true },
    quantityButtonsWrapperClass: { type: [Array, String], default: () => [] },
  },
  data() {
    return {
      quantity: 1,
    }
  },
  watch: {
    quantity: {
      handler(val) {
        this.$emit('input', val)
      },
    },
    value: {
      handler(val) {
        if (typeof val === 'number' && val !== this.quantity && val >= this.minRange && val <= this.maxRange) {
          this.quantity = val
        }
      },
      immediate: true,
    },
  },
  computed: {
    min() {
      return this.quantity <= this.minRange
    },
    max() {
      return this.quantity >= this.maxRange
    },
  },
  methods: {
    quantityFormatter(val) {
      if (val > this.maxRange) {
        return this.maxRange
      } else if (val < this.minRange || val === '') {
        return this.minRange
      }
      return Number.parseInt(val)
    },
    increment() {
      if (this.quantity < this.maxRange) {
        this.quantity++
      }
    },
    decrement() {
      if (this.quantity > this.minRange) {
        this.quantity--
      }
    },
  },
}
</script>
