<template>
  <b-row class="align-items-baseline">
    <b-col cols="auto">
      <b-button variant="white" :disabled="min" class="p-0 rounded-circle border-0" @click="decrement">
        <b-icon icon="dash-circle" font-scale="1.5" :variant="min ? 'black-50' : 'primary'" />
      </b-button>
    </b-col>

    <b-col cols="auto" class="px-0">
      <b-form-input
        number
        disabled
        size="sm"
        type="number"
        :min="minRange"
        :max="maxRange"
        v-model="quantity"
        class="text-center bg-white"
        :class="{ 'rounded-0': squared }"
      />
    </b-col>

    <b-col cols="auto">
      <b-button variant="white" :readonly="max" class="p-0 rounded-circle border-0" @click="increment">
        <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: {
    value: { type: [Number, String], default: 1 },
    minRange: { type: Number, default: 1 },
    maxRange: { type: Number, default: 100 },
    squared: { type: Boolean, default: false },
  },
  data() {
    return {
      quantity: 1,
    }
  },
  watch: {
    quantity: {
      handler(val) {
        if (val > this.maxRange || val < this.minRange || val === '') {
          this.quantity = 1
        }
        this.$emit('input', val)
      },
      immediate: true,
    },
  },
  computed: {
    min() {
      return this.quantity <= this.minRange
    },
    max() {
      return this.quantity >= this.maxRange
    },
  },
  mounted() {
    if (typeof this.value === 'number' && this.value > this.minRange && this.value <= this.maxRange) {
      this.quantity = this.value
    }
  },
  methods: {
    increment() {
      if (this.quantity < this.maxRange) {
        this.quantity++
      }
    },
    decrement() {
      if (this.quantity > this.minRange) {
        this.quantity--
      }
    },
  },
}
</script>
