<template>
  <layout>
    <b-row class="center-align p-4">
      <b-col cols="auto">
        <b-row align-h="center">
          <b-col cols="auto">
            <b-img :src="getLogo" class="icon-size-7" />
          </b-col>
          <b-col v-if="step === 'start'" cols="12" class="text-center">
            <h5 class="mt-3">
              {{ $t('OnBehalf.LoggingIn') }}
            </h5>
            <b-spinner variant="primary" />
          </b-col>
          <b-col cols="12" v-if="step === 'failed'" class="text-center">
            <h5 class="mt-3">{{ $t('OnBehalf.Invalid') }}</h5>
            <b-button variant="danger" @click="redirect">{{ $t('OnBehalf.Redirect') }}</b-button>
          </b-col>
        </b-row>
      </b-col>
    </b-row>
  </layout>
</template>
<script>
import layout from './templates/Layout'
import { mapActions } from 'vuex'
import IbsLogo from '@/assets/img/ibs-logo.png'
import EvoLogo from '@/assets/img/Evo/evo-logo-square.png'
import { LOGIN_URL } from '@/config/defaults'
import { API_TOKEN } from '@/store/utils/localStorageKeys'

export default {
  name: 'LoginOnBehalf',
  components: { layout },
  data() {
    return {
      step: 'start',
    }
  },
  mounted() {
    // validate
    let self = this
    let query = this.$route.query
    let whiteListMedium = ['wp']
    if (typeof query.token !== 'undefined') {
      // if is_member = true will skip on behalf checking
      self
        .loginUser({
          response: {
            data: {
              access_token: query.token,
              token_type: query.token_type || 'Bearer',
              expires_in: query.expires_in || 2592000,
              on_behalf: whiteListMedium.includes(query.medium) ? false : query.is_member === undefined,
            },
          },
        })
        .then(res => {
          if (query.medium === 'wp') {
            self.wordPressRedirectHandler(res instanceof Error, query)
          } else if (!(res instanceof Error)) {
            self.$nextTick(() => {
              this.redirect()
            })
          } else {
            self.step = 'failed'
          }
        })
    } else {
      self.step = 'failed'
    }
  },
  methods: {
    ...mapActions(['loginUser', 'guestLogin']),
    ...mapActions('eshop', ['setPreserveCartState']),
    redirect(location, sponsorId = false) {
      let route =
        (location === 'eshopCheckout' && { name: 'Checkout' }) ||
        (location === 'enrolment' && { name: 'New Enrolment' }) ||
        LOGIN_URL

      if (location === 'enrolment' && sponsorId) {
        route['params'] = { sponsorID: sponsorId }
      }
      this.$router.replace(route)
    },
    wordPressRedirectHandler(isGuess, { token, sponsorId }) {
      let self = this
      let actions = isGuess ? self.guestLogin({ accessToken: token }) : Promise.resolve({ user_type: 'member' })
      actions.then(response => {
        if (response && response.user_type) {
          if (isGuess) {
            this.setPreserveCartState(true)
            localStorage.removeItem(API_TOKEN)
          }
        }
      })

      self.$nextTick(() => {
        this.redirect((isGuess && 'enrolment') || 'eshopCheckout', sponsorId)
      })
    },
  },
  computed: {
    getLogo() {
      return this.$appSettings.evo.enable ? EvoLogo : IbsLogo
    },
  },
}
</script>
