<template>
  <el-select
    v-model="value"
    :clearable="isDesktop"
    :placeholder="$t('usersFilter.inputPlaceholder')"
    multiple
    class="select-field"
    @change="toggleFilters">
    <el-option-group :label="$t('usersFilter.byAccountType')">
      <el-option value="local" label="Local">{{ $t('usersFilter.local') }}</el-option>
      <el-option value="external" label="External">{{ $t('usersFilter.external') }}</el-option>
    </el-option-group>
    <el-option-group :label="$t('usersFilter.byStatus')">
      <el-option value="active" label="Active">{{ $t('usersFilter.active') }}</el-option>
      <el-option value="need_approval" label="Need Approval">{{ $t('usersFilter.pending') }}</el-option>
      <el-option value="deactivated" label="Deactivated">{{ $t('usersFilter.deactivated') }}</el-option>
    </el-option-group>
  </el-select>
</template>

<script>
export default {
  data() {
    return {
      value: ['local', 'active']
    }
  },
  computed: {
    isDesktop() {
      return this.$store.state.app.device === 'desktop'
    }
  },
  created() {
    const currentFilters = this.$data.value.reduce((acc, filter) => ({ ...acc, [filter]: true }), {})
    this.$store.dispatch('ToggleUsersFilter', currentFilters)
  },
  methods: {
    removeOppositeFilters() {
      const filtersQuantity = Object.keys(this.$store.state.users.filters).length
      const currentFilters = []
      const indexOfLocal = this.$data.value.indexOf('local')
      const indexOfExternal = this.$data.value.indexOf('external')
      const indexOfActive = this.$data.value.indexOf('active')
      const indexOfDeactivated = this.$data.value.indexOf('deactivated')
      const indexOfPending = this.$data.value.indexOf('need_approval')

      if (this.$data.value.length === filtersQuantity) {
        return []
      }

      Math.max(indexOfLocal, indexOfExternal) > -1
        ? currentFilters.push(this.$data.value[Math.max(indexOfLocal, indexOfExternal)])
        : currentFilters

      Math.max(indexOfActive, indexOfDeactivated, indexOfPending) > -1
        ? currentFilters.push(this.$data.value[Math.max(indexOfActive, indexOfDeactivated, indexOfPending)])
        : currentFilters

      return currentFilters
    },
    toggleFilters() {
      this.$data.value = this.removeOppositeFilters()
      const currentFilters = this.$data.value.reduce((acc, filter) => ({ ...acc, [filter]: true }), {})
      this.$store.dispatch('ToggleUsersFilter', currentFilters)
    }
  }
}
</script>

<style rel='stylesheet/scss' lang='scss' scoped>
.select-field {
  width: 350px;
}

@media only screen and (max-width:480px) {
  .select-field {
    width: 100%;
    margin-bottom: 5px;
  }
}
</style>
