<template>
  <div class="py-1 px-1 small text-muted">
    <itf-label :label="$t('components.filter.filterBy')" hide-details class="w-100">
      <itf-select
        v-model="filterType"
        :options="filterTypes"
        :get-option-label="option => option.text"
        :reduce="option => option.value"
        @input="onChangeType"
      />
    </itf-label>

    <itf-label v-if="filterType === 'exact'" :label="$t('components.filter.value')" hide-details class="mb-0 w-100">
      <itf-text-field type="number" :value="internalValue" @input="onChange($event)" />
    </itf-label>
    <div v-else-if="internalValue" class="d-flex justify-content-between gap-2">
      <itf-label :label="$t('components.filter.from')" hide-details class="mb-0 w-100">
        <itf-text-field type="number" :value="internalValue[0]" @input="onChange([$event, internalValue[1]])" />
      </itf-label>
      <itf-label :label="$t('components.filter.to')" hide-details class="mb-0 w-100">
        <itf-text-field type="number" :value="internalValue[1]" @input="onChange([internalValue[0], $event])" />
      </itf-label>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.histogram {
  display: flex;
  justify-content: space-between;
  align-items: end;
  gap: .25rem;
  border-bottom: 1px solid #AAA;

  & > div {
    background: var(--bs-primary);
    flex-grow: 1;
    height: var(--bar-height);
  }
}
</style>
<script>
import { Vue, Prop, Model, Component } from 'vue-property-decorator';
import itfLabel from '../form/Label.vue';
import itfSelect from '../select/Select.vue';
import itfTextField from '../text-field/TextField.vue';
import itfRange from '../range/Range.vue';
import debounce from 'lodash/debounce';

export default @Component({
  name: 'FilterAmountRange',
  components: {
    itfSelect,
    itfTextField,
    itfLabel,
    itfRange
  }
})
class FilterAmountRange extends Vue {
  @Model('input') value;
  @Prop() min;
  @Prop() max;
  @Prop() histogram;

  filterType = false;
  internalValue = 'exact';
  onChangeFn = null;

  get filterTypes() {
    return [
      { text: this.$t('components.filter.exact'), value: 'exact' },
      { text: this.$t('components.filter.range'), value: 'range' }
    ];
  }

  mounted() {
    this.internalValue = this.value;
    this.filterType = Array.isArray(this.internalValue) ? 'range' : 'exact';
    this.onChangeFn = debounce(() => {
      this.$emit('input', this.internalValue);
    }, 500);
  }

  onChange(val) {
    this.internalValue = val;
    if (!Number.isNaN(parseFloat(val))) {
      this.onChangeFn()
    }
    if (!val) {
      this.onChangeFn();
    }
  }

  onChangeType(type) {
    if (type === 'range') {
      this.internalValue = [parseFloat(this.internalValue), parseFloat(this.internalValue)];
    } else {
      this.internalValue = Array.isArray(this.internalValue) ? parseFloat(this.internalValue[0]) : parseFloat(this.internalValue);
    }
  }
}
</script>
