<template>
  <div class="eshop-items-filter-panel">
    <div v-if="showPayCycleDropdown" class="item">
      <h6>{{ $t('Common.Terminology.PayCycle') }}</h6>
      <b-select :options="getPayCycleList" v-model="selectedPayCycle" />
    </div>
    <div class="item" v-if="getMemberEnrollmentRank.sales_types">
      <h6>{{ $t('Eshop.LeftPanel.SalesType') }}</h6>
      <b-form-checkbox
        v-for="type in getMasterDataKeysByKeysTitles('sale_types', getMemberEnrollmentRank.sales_types.values)"
        stacked
        :value="type.id"
        v-model="selectedTypes"
        :disabled="type.id === repurchaseId && selectedTypes && selectedTypes.indexOf(repurchaseId) !== -1"
        :key="`saletype-${type.id}`"
        :data-qa="$helpers.kebabCase(`eshop-sales-type-filter-panel-${type.title}-checkbox`)"
      >
        {{ $t(`Master.SaleTypes.${type.title}`) }}
      </b-form-checkbox>
    </div>
    <div class="item d-md-none" v-if="getSortedProductMainCategoriesOptions.length !== 0">
      <h6>{{ $t('Eshop.LeftPanel.Category') }}</h6>
      <b-form-radio-group v-model="categoryModel" stacked>
        <b-form-radio
          v-for="category in getSortedProductMainCategoriesOptions"
          :key="`category-${category.value}`"
          :value="category.value"
          class="inverse"
          :data-qa="$helpers.kebabCase(`eshop-category-filter-panel-${category.text}-checkbox`)"
          stacked
        >
          {{ category.text }}
        </b-form-radio>
      </b-form-radio-group>
    </div>
    <div class="item" v-if="showSubCategory && getProductCurrentSubCategories.length !== 0">
      <h6>{{ $t('Eshop.LeftPanel.SubCategories') }}</h6>
      <b-form-checkbox
        class="inverse"
        v-model="allSubCategories"
        @change="toggleAllSubCategory"
        :disabled="this.subCategories.length === 0"
        stacked
      >
        {{ $t('Eshop.LeftPanel.SubCategoriesAll') }}
      </b-form-checkbox>
      <b-form-checkbox
        v-for="subCategory in getProductCurrentSubCategories"
        :key="`subcategories-${subCategory.id}`"
        :value="subCategory.id"
        v-model="subCategories"
        class="inverse"
        stacked
      >
        {{ $helpers.getValue(subCategory, 'translated_name.content', subCategory.name) }}
      </b-form-checkbox>
    </div>
    <div v-if="showPriceFilter" class="item">
      <h6>{{ $t('Eshop.LeftPanel.Price.Title', { currency: currency }) }}</h6>
      <div class="custom-eshop-range-slider">
        <b-form-slider :min="priceMin" :max="priceMax" v-model="priceRange" @slide-stop="updatePriceRange" />
        <div class="range-inputs mt-2">
          <b-form-input
            type="number"
            @change="updatePriceRange"
            v-model="priceMinModel"
            :placeholder="$t('Eshop.LeftPanel.Price.Min')"
            class="rounded-1"
          />
          <icon name="minus" class="separator" />
          <b-form-input
            type="number"
            @change="updatePriceRange"
            v-model="priceMaxModel"
            :placeholder="$t('Eshop.LeftPanel.Price.Max')"
            class="rounded-1"
          />
          <b-button variant="primary" @click="updatePriceRange">
            <icon name="chevron-right" />
          </b-button>
        </div>
      </div>
    </div>
    <div v-if="showBvFilter" class="item">
      <h6>{{ $t('Eshop.LeftPanel.CV.Title') }}</h6>
      <div class="custom-eshop-range-slider">
        <b-form-slider :min="cvMin" :max="cvMax" range v-model="cvRange" @slide-stop="updateCvRange" />
        <div class="range-inputs mt-2">
          <b-form-input
            type="text"
            @change="updateCvRange"
            v-model="cvMinModel"
            :placeholder="$t('Eshop.LeftPanel.CV.Min')"
            class="rounded-1"
          />
          <icon name="minus" class="separator" />
          <b-form-input
            type="text"
            @change="updateCvRange"
            v-model="cvMaxModel"
            :placeholder="$t('Eshop.LeftPanel.CV.Max')"
            class="rounded-1"
          />
          <b-button variant="primary" @click="updateCvRange">
            <icon name="chevron-right" />
          </b-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
import { CurrencyMixin, mapMasterDataId } from '@/app/_global/mixins'
import helpers from '@/helpers'

export default {
  name: 'ItemsFilterPanel',
  mixins: [CurrencyMixin],
  props: {
    showPayCycleDropdown: { type: Boolean, default: false },
    showSubCategory: { type: Boolean, default: true },
    showPriceFilter: { type: Boolean, default: true },
    showBvFilter: { type: Boolean, default: true },
  },
  data() {
    return {
      selectedTypes: [],
      subCategories: [],
      allSubCategories: true,
      indeterminateSubCategory: false,
      priceMin: 0,
      priceMax: 0,
      cvMin: 0,
      cvMax: 0,
      priceMinModel: 0,
      priceMaxModel: 0,
      cvMinModel: 0,
      cvMaxModel: 0,
      priceRange: [0, 0],
      cvRange: [0, 0],
      propagateSalesType: true,
      selectedSvMonth: null,
      payCycles: [],
      selectedPayCycle: null,
      payCycleFilter: { filter_type: 'current', sort: 'id', order: 'desc', limit: 2 },
    }
  },
  mounted() {
    if (this.showPayCycleDropdown) {
      this.loadCwScheduleList(this.payCycleFilter).then(cycles => {
        this.payCycles = cycles || []
        this.selectedPayCycle =
          (this.payCycles.find(cycle => cycle.default) || {}).id || (this.payCycles[0] && this.payCycles[0].id) || null
      })
    }
    // Set Initial data from state
    // Uses finally method here is for setting the sales type value even though the master data request fail
    this.resolveMasters.finally(() => {
      if (
        this.$helpers
          .getValue(this.getMemberEnrollmentRank, 'sales_types.values', [])
          .includes(this.$const.masterData['REGISTRATION'])
      ) {
        this.selectedTypes = [this.registrationId]
      } else {
        this.selectedTypes = this.getFilteredSalesTypes
      }
    })
    this.subCategories = this.getProductSelectedSubCategories
    this.toggleAllSubCategory()
  },
  computed: {
    ...mapGetters([
      'getMasterDataKeysByKeysTitles',
      'getMemberEnrollmentRank',
      'getLayoutMode',
      'getMasterDataTitleByKeyAndId',
      'getMasterDataIdByKeyAndTitle',
    ]),
    ...mapGetters('eshop', [
      'getProductCurrentSubCategories',
      'getFilteredSalesTypes',
      'getFilteredPriceRange',
      'getFilteredCvRange',
      'getProductSelectedSubCategories',
      'getSortedProductMainCategoriesOptions',
      'getProductCurrentCategory',
      'getBaSalesTypeId',
      'getAvailableFilters',
    ]),
    ...mapMasterDataId({
      SALE_TYPES: {
        repurchaseId: 'RE_PURCHASE',
        registrationId: 'REGISTRATION',
        rentalId: 'RENTAL',
      },
    }),
    filterPannelMobile() {
      return this.getLayoutMode('filter-panel', 'hide') !== 'hide'
    },
    categoryModel: {
      get() {
        return this.getProductCurrentCategory.id
      },
      set(categoryId) {
        this.productChangeCurrentCategory(categoryId)
      },
    },
    getPayCycleList() {
      return this.payCycles.map(cycle => ({
        text: this.$t('Common.Terminology.PayCycle.Placeholder', { pc: cycle.cw_name }),
        value: cycle.id,
      }))
    },
  },
  methods: {
    ...mapActions('eshop', [
      'filterProductsForSaleTypes',
      'filterEkSmartProducts',
      'filterProductPriceRange',
      'filterProductCvRange',
      'filterProductsSubCategory',
      'productChangeCurrentCategory',
      'setCartSalesCwId',
    ]),
    ...mapActions(['layoutBlocks', 'loadCwScheduleList']),
    toggleAllSubCategory(val) {
      if (this.subCategories.length === 0) {
        this.allSubCategories = true
      } else if (this.subCategories.length === this.getProductCurrentSubCategories.length) {
        this.allSubCategories = true
      } else {
        if (val === true) {
          this.subCategories = []
        } else {
          this.allSubCategories = false
        }
      }
    },
    updatePriceRange() {
      let priceMin = this.$helpers.getNumberValue(this.priceMinModel) || 0
      let newMin = priceMin === 0 ? 0 : priceMin
      let priceMax = this.$helpers.getNumberValue(this.priceMaxModel) || 0
      let newMax = priceMax === 0 ? this.priceMax : priceMax
      this.priceRange = [newMin, newMax]
      this.filterProductPriceRange({ value: this.priceRange, isInitial: false })
    },
    updateCvRange() {
      let cvMin = this.$helpers.getNumberValue(this.cvMinModel) || 0
      let newMin = cvMin === 0 ? 0 : cvMin
      let cvMax = this.$helpers.getNumberValue(this.cvMaxModel) || 0
      let newMax = cvMax === 0 ? this.cvMax : cvMax
      this.cvRange = [newMin, newMax]
      this.filterProductCvRange({ value: this.cvRange, isInitial: false })
    },
    filterPanelOff() {
      this.layoutBlocks({ block: 'filter-panel', layout: 'hide' })
    },
  },
  watch: {
    selectedTypes(to, from) {
      if (this.propagateSalesType && to) {
        if (to.length === 0) {
          if (
            this.$helpers
              .getValue(this.getMemberEnrollmentRank, 'sales_types.values', [])
              .includes(this.$const.masterData['REGISTRATION'])
          ) {
            this.selectedTypes = [this.registrationId]
          } else {
            this.selectedTypes = [this.repurchaseId]
          }
        } else {
          this.selectedTypes = to.filter(value => from.indexOf(value) === -1)
        }
        this.filterProductsForSaleTypes(this.selectedTypes)
        let rentalTypeKey
        if (this.rentalId) {
          rentalTypeKey = this.rentalId
        } else {
          rentalTypeKey = this.getMasterDataIdByKeyAndTitle('sale_types', 'RENTAL')
        }
        let isEkSmart = false
        if (rentalTypeKey === this.selectedTypes[0]) {
          isEkSmart = true
        }
        this.filterEkSmartProducts(isEkSmart)
        this.propagateSalesType = false
      } else {
        this.propagateSalesType = true
      }
    },
    priceRange() {
      if (this.priceRange != null) {
        if (typeof this.priceRange[0] !== 'undefined' && this.priceRange[0] !== 0) {
          this.priceMinModel = this.$helpers.getNumberValue(this.priceRange[0], 0)
        } else {
          this.priceMinModel = ''
        }
        if (typeof this.priceRange[1] !== 'undefined' && this.priceRange[1] !== this.priceMax) {
          this.priceMaxModel = this.$helpers.getNumberValue(this.priceRange[1], 0)
        } else {
          this.priceMaxModel = ''
        }
      }
    },
    cvRange() {
      if (this.cvRange != null) {
        if (typeof this.cvRange[0] !== 'undefined' && this.cvRange[0] !== 0) {
          this.cvMinModel = this.$helpers.getNumberValue(this.cvRange[0], 0)
        } else {
          this.cvMinModel = ''
        }
        if (typeof this.cvRange[1] !== 'undefined' && this.cvRange[1] !== this.cvMax) {
          this.cvMaxModel = this.$helpers.getNumberValue(this.cvRange[1], 0)
        } else {
          this.cvMaxModel = ''
        }
      }
    },
    subCategories() {
      this.toggleAllSubCategory()
      this.filterProductsSubCategory(this.allSubCategories === true ? [] : this.subCategories)
    },
    getAvailableFilters: {
      async handler(filters) {
        this.priceMin = helpers.getNumberValue(filters.price_range.min)
        this.priceMax = helpers.getNumberValue(filters.price_range.max)
        this.cvMin = helpers.getNumberValue(filters.cv_range.min)
        this.cvMax = helpers.getNumberValue(filters.cv_range.max)
        this.$nextTick(() => {
          this.priceRange = this.getFilteredPriceRange
          this.cvRange = this.getFilteredCvRange
        })
      },
      deep: true,
    },
    selectedPayCycle: {
      handler(val) {
        this.setCartSalesCwId(val)
      },
      immediate: true,
    },
  },
}
</script>
