<template>
  <tabs-template>
    <h4>{{ $t('MyAccount.PlacementPreference.HeaderText') }}</h4>
    <p class="mt-4">{{ $t('MyAccount.PlacementPreference.BodyText') }}</p>

    <b-row class="pt-3 ml-md-3 ml-0">
      <b-col md="4" sm="12" class="text-left text-md-right pl-0 pl-md-3">
        <label class="required">
          {{ $t('MyAccount.PlacementPreference.DefaultPlacementText') }}
        </label>
      </b-col>
      <b-col md="8" sm="12" class="pl-0 pl-md-3">
        <b-form-radio-group v-model="selectedPreference" :options="placementOptions" />
      </b-col>
    </b-row>

    <div class="text-center mt-4">
      <strong>
        {{ $t('MyAccount.PlacementPreference.NextPlacementText') }} :
        {{ placementValueMap[getPlacementPreference.next_placement] }}
      </strong>
    </div>

    <div class="mt-2 text-center">
      <b-btn variant="primary" class="m-2" @click="update()" :disabled="isLoading">
        <icon name="spinner" pulse v-if="isLoading" />
        <template v-else>
          {{ $t('Common.Update') }}
        </template>
      </b-btn>
    </div>

    <b-modal ref="savePreference" class="eshop-model" ok-only size="sm" hide-header centered>
      <h5>{{ $t('MyAccount.PlacementPreference.SavedSuccessText') }}</h5>
    </b-modal>
  </tabs-template>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
import MyAccountTabsTemplate from './templates/MyAccountTabsTemplate'

export default {
  name: 'PlacementPreference',
  components: {
    TabsTemplate: MyAccountTabsTemplate,
  },
  computed: {
    ...mapGetters(['getPlacementPreference']),
  },
  data() {
    return {
      selectedPreference: 0,
      placementOptions: [
        { text: this.$t('MyAccount.PlacementPreference.OptionAutomatic'), value: 0 },
        { text: this.$t('MyAccount.PlacementPreference.OptionLeft'), value: 1 },
        { text: this.$t('MyAccount.PlacementPreference.OptionRight'), value: 2 },
      ],
      placementValueMap: {
        0: this.$t('MyAccount.PlacementPreference.OptionAutomatic'),
        1: this.$t('MyAccount.PlacementPreference.OptionLeft'),
        2: this.$t('MyAccount.PlacementPreference.OptionRight'),
      },
      isLoading: false,
    }
  },
  async mounted() {
    await this.loadPlacementPreference().then(() => {
      this.selectedPreference = this.getPlacementPreference.preference
    })
  },
  methods: {
    ...mapActions(['loadPlacementPreference', 'updatePlacementPreference']),
    async update() {
      this.isLoading = true

      await this.updatePlacementPreference({
        preference: this.selectedPreference,
      }).then(() => {
        this.selectedPreference = this.getPlacementPreference.preference

        this.$refs.savePreference.show()
      })

      this.isLoading = false
    },
  },
}
</script>
