<template>
  <div class="content">
    <div class="enrol-banner" :style="{ backgroundImage: `url('${getEnrolBackground}')` }">
      <b-button :to="{ path: '/' }" variant="link" class="mt-2">
        <icon name="back-icon" class="icon-size-4 text-white" />
      </b-button>
      <div class="enrol-banner-brand">
        <div>
          <b-img :src="MainLogo" center class="icon-size-5 mb-4" />
        </div>
        <div v-if="!isEvo" class="text">
          <h1>{{ $t('Enrolment.Enrolment.Title') }}</h1>
        </div>
      </div>
      <enrolment-footer display-only />
    </div>
    <div class="enrol-personal-data-wrapper">
      <b-form class="enrol-personal-data-step" id="enrol-personal-data-step-form">
        <div v-if="isEvo" class="pb-1">
          <h2 class="font-size-2 font-size-lg-1">{{ $t('Enrolment.Landing.Form.Title') }}</h2>
          <p class="font-size-5">{{ $t('Enrolment.Landing.Form.Subtitle') }}</p>
        </div>
        <div>
          <b-form-group>
            <b-form-radio-group
              buttons
              size="lg"
              class="w-100 bg-white"
              @input="changeMembership"
              button-variant="outline-primary"
              v-model="enrolmentData.membershipType"
            >
              <b-form-radio
                value="Standard"
                class="py-3"
                data-qa="enrolment-planSelectionPage-standardMembership-radio"
              >
                {{ $t('Enrolment.MembershipLabel.Standard') }}
              </b-form-radio>
              <b-form-radio value="EK Smart" class="py-3" data-qa="enrolment-planSelectionPage-ekSmartMembership-radio">
                {{ $t('Common.EKSmart') }}
              </b-form-radio>
            </b-form-radio-group>
          </b-form-group>
        </div>
        <div>
          <label>{{ $t('Enrolment.Landing.Form.Region') }}</label>
          <div :class="{ 'initializing-light-extra': isLoading(['loadingGeoCountry', 'loadCountries']) }">
            <v-select
              label="text"
              @input="countryManipulation"
              :options="countriesOptions"
              v-model="enrolmentData.region"
              data-qa="enrolment-planSelectionPage-region-select"
            >
              <template slot="selected-option">
                <span>{{ getSelectedCountryName }}</span>
              </template>
            </v-select>
          </div>
        </div>
        <div>
          <label>{{ $t('Enrolment.Landing.Form.Language') }}</label>
          <div :class="{ 'initializing-light-extra': isLoading(['loadingGeoCountry', 'loadLanguages']) }">
            <v-select
              label="text"
              @input="languageManipulation"
              :options="languagesOptions"
              v-model="enrolmentData.language"
              class="preferred-language-dropdown"
              data-qa="enrolment-planSelectionPage-language-select"
            >
              <template slot="selected-option" slot-scope="option">
                <span v-if="option.key" class="text-badge py-1">{{ option.key }}</span>
                <span class="pl-2">{{ option.text }}</span>
              </template>
              <template slot="option" slot-scope="option">
                <span v-if="option.key" class="text-badge py-1">{{ option.key }}</span>
                <span class="pl-2">{{ option.text }}</span>
              </template>
            </v-select>
          </div>
        </div>
        <div v-if="!isEvo" class="info-box-wrapper">
          <label>{{ $t('Enrolment.Landing.Form.Type') }}</label>
          <b-skeleton-wrapper
            :loading="isLoading('getEnrolmentTypes') || enrolmentTypes.length < 1 || loadingMembershipData"
          >
            <template v-slot:loading>
              <b-row>
                <b-col><b-skeleton class="card-container"/></b-col>
                <b-col v-if="enrolmentData.membershipType !== 'EK Smart'"><b-skeleton class="card-container"/></b-col>
              </b-row>
            </template>

            <b-row>
              <b-col v-for="(enrolment, index) in enrolmentTypes" :key="index" class="mb-2">
                <b-card
                  :class="{ flash: highlightTypes }"
                  class="h-100 card-container animated"
                  body-class="d-flex flex-column p-2"
                  :border-variant="enrolment.id === enrolmentData.enrolment_type ? 'primary' : 'light'"
                >
                  <div>
                    <b-button
                      :id="`enrolment-${index}`"
                      size="small"
                      variant="reset"
                      class="rounded-circle float-right p-0"
                      @click="$root.$emit('bv::enable::popover', `enrolment-${index}`)"
                    >
                      <icon name="info-circle-icon" class="text-black-50" />
                    </b-button>
                  </div>
                  <div class="text-center mt-auto mb-2">
                    <h6 class="font-weight-bolder">{{ getEnrolmentRankTitle(enrolment.title) }}</h6>
                    <b-button
                      pill
                      size="sm"
                      class="mt-2 action-button"
                      @click="setEnrolmentType(enrolment.id)"
                      :variant="enrolment.id === enrolmentData.enrolment_type ? 'primary' : 'light'"
                      :data-qa="
                        `enrolment-planSelectionPage-enrolmentType${$helpers.kebabCase(enrolment.title)}-button`
                      "
                    >
                      <icon v-if="enrolment.id === enrolmentData.enrolment_type" name="check" />
                      <span v-else>
                        {{ $t('Common.Choose') }}
                      </span>
                    </b-button>
                  </div>
                </b-card>
                <b-popover
                  placement="left"
                  :target="`enrolment-${index}`"
                  :key="`enrolment-tooltip-${index}`"
                  container="enrol-personal-data-step-form"
                  ref="popover"
                >
                  <div class="info-title-tooltip-content">
                    <button @click="$root.$emit('bv::hide::popover')" type="button" class="close" aria-label="Close">
                      <icon name="close-icon" class="icon-size-3" />
                    </button>
                    <div class="info-popover-title">
                      {{ getEnrolmentRankTitle(enrolment.title) }}
                    </div>
                    <div class="info-popover-info" v-html="getEnrolmentInfo(enrolment.title)" />
                  </div>
                </b-popover>
              </b-col>
            </b-row>
          </b-skeleton-wrapper>
        </div>
        <div>
          <label>{{ $t('Enrolment.Landing.Form.Sponsor') }}</label>
          <search-sponsor-input-group
            :enrolment-data="enrolmentData"
            @undisabled="clearDontKnowSponsor"
            :class="{ flash: highlightSponsor }"
            class="animated overflow-hidden border rounded-1"
            :show-action-button="!Boolean($route.query.redirect)"
          />
          <div v-show="!enrolmentData.sponsor_member_id" class="mt-3">
            <b-form-checkbox
              :value="1"
              :unchecked-value="0"
              v-model="enrolmentData.without_sponsor"
              @input="controlInputs('withoutSponsor')"
              data-qa="enrolment-planSelectionPage-withoutSponsor-checkbox"
            >
              {{ $t('Enrolment.DoNotKnowMySponsor.Text') }}
            </b-form-checkbox>
            <h6 class="text-info-green mt-3" v-if="enrolmentData.without_sponsor === 1">
              {{ $t('Enrolment.Form.Sponsor.Info') }}
            </h6>
          </div>
        </div>
        <div class="mt-4">
          <b-button
            block
            size="lg"
            @click="continueNext"
            :variant="loadingMembershipData || getEnrolmentTypeState ? 'primary' : 'danger'"
            :disabled="loadingMembershipData || !getEnrolmentTypeState"
            data-qa="enrolment-planSelectionPage-enrol-btn"
          >
            <span v-if="!(loadingMembershipData || getEnrolmentTypeState)">
              {{ $t('Enrolment.Landing.Form.EnrolTypeMissing') }}
            </span>
            <span v-else class="pl-2">{{ next }}</span>
          </b-button>
          <b-button
            block
            variant="link"
            class="mt-3"
            @click="$refs.resumeEnrolmentModel.show()"
            data-qa="enrolment-planSelectionPage-resumeEnrolment-btn"
          >
            <span>{{ $t('Enrolment.Form.ResumeEnrolment.Button') }}</span>
          </b-button>
        </div>
      </b-form>
    </div>
    <b-modal
      size="sm"
      hide-footer
      no-close-on-backdrop
      no-close-on-esc
      class="enrol-resume-model enrol-section"
      :title="$t('Enrolment.Resume.Title')"
      centered
      ref="resumeEnrolmentModel"
    >
      <div v-if="!isLoading('applyTempEnrolmentData') && !isLoading('getEnrolmentData')" class="enrol-section-content">
        <b-row class="enrol-controls-holder">
          <b-col cols="12" class="enrol-section-label">
            <label class="required">
              {{ $t('Enrolment.ResumeCode.Label') }}
            </label>
          </b-col>
          <b-col cols="12" class="enrol-section-controls">
            <b-form-input
              size="lg"
              type="text"
              @input="removeError('getEnrolmentData')"
              @keyup.enter="resumeEnrolment()"
              :name="$t('Enrolment.ResumeCode.Label')"
              v-model="enrolmentResumeCode"
              v-validate="'required'"
            />
          </b-col>
          <b-col cols="12" class="enrol-section-controls-errors">
            <span
              v-show="!getErrorsState('getEnrolmentData')"
              class="help invalid validated"
              v-for="(error, errorIdx) in getErrorsBreakup('getEnrolmentData')"
              :key="errorIdx"
            >
              {{ Array.isArray(error) ? error.toString() : error }}
            </span>
          </b-col>
        </b-row>
        <b-row class="enrol-controls-holder pt-2" align-h="end">
          <b-col cols="auto">
            <b-button @click="resumeEnrolment" variant="primary" :disabled="enrolmentResumeCode === ''">
              <icon name="spinner" pulse v-if="isLoading('getEnrolmentData')" />
              {{ $t('Common.Continue') }}
            </b-button>
          </b-col>
        </b-row>
      </div>
      <div v-else>
        <b-row align-v="center">
          <b-col class="d-flex align-items-center">
            <b-spinner variant="primary" class="mr-2" />
            <span>
              {{ isLoading('getEnrolmentData') ? $t('Enrolment.Loading.Info') : $t('Enrolment.Applying.Info') }}
            </span>
          </b-col>
        </b-row>
      </div>
    </b-modal>
  </div>
</template>
<script>
import _ from 'lodash'
import EnrolmentBanner from '@/assets/img/img-enrol-hub.png'
import EvoBanner from '@/assets/img/Evo/evo-login-bg.svg'
import searchSponsorInputGroup from '@/app/enrolment/_global/components/elements/searchSponsorInputGroup'
import EnrolmentFooter from '@/app/enrolment/_global/components/blocks/EnrolmentFooter'
import { mapActions, mapGetters, mapMutations } from 'vuex'
import { SELECTED_LANGUAGE } from '@/store/utils/localStorageKeys'

export default {
  components: { searchSponsorInputGroup, EnrolmentFooter },
  name: 'EnrolmentPlanSelectionPage',
  props: {
    applyTempEnrolmentData: {
      type: Function,
      required: true,
    },
    sponsor: {
      default: null,
    },
    enrolmentData: {
      type: Object,
      required: true,
    },
    previous: {
      type: String,
    },
    next: {
      type: String,
    },
    prevAction: {
      type: Function,
    },
    nextAction: {
      type: Function,
    },
  },
  $_veeValidate: {
    validator: 'new',
  },
  computed: {
    ...mapGetters({
      countriesOptions: 'getCountries',
      languagesOptions: 'getLanguageList',
      isLoading: 'isLoading',
      getErrorsState: 'getErrorsState',
      getErrorsBreakup: 'getErrorsBreakup',
      getSelectedLanguage: 'getSelectedLanguage',
      getLoggedInUser: 'getLoggedInUser',
      afterLoading: 'afterLoading',
      getDefaultPreferredGeoLanguage: 'getDefaultPreferredGeoLanguage',
      getDefaultPreferredGeoCountry: 'getDefaultPreferredGeoCountry',
    }),
    ...mapGetters('enrolment', {
      getEnrolForm: 'getEnrolForm',
      getEnrolAddress: 'getEnrolAddress',
      enrolmentTypes: 'getEnrolmentTypes',
      getTempSmsCode: 'getTempSmsCode',
      getUpgradeDetails: 'getUpgradeDetails',
      getEnrolmentLanguage: 'getEnrolmentLanguage',
    }),
    getEnrolBackground() {
      return this.isEvo ? this.evoBanner : this.enrolmentBanner
    },
    getEnrolmentTypeState() {
      return this.enrolmentTypes.length > 0 && this.foundEvoDefaultEnrolType
    },
    getSelectedCountryName() {
      if (this.$helpers.getValue(this.enrolmentData, 'region.value') && this.countriesOptions.length) {
        return this.countriesOptions.find(country => country.value === this.enrolmentData.region.value).text
      }
      return ''
    },
  },
  data() {
    return {
      enrolmentBanner: EnrolmentBanner,
      evoBanner: EvoBanner,
      MainLogo: this.$const.constImage.COMPANY_LOGO,
      show: '',
      enrolmentResumeCode: '',
      highlightTypes: false,
      highlightSponsor: false,
      isEvo: this.$appSettings.evo.enable,
      loadingMembershipData: false,
      foundEvoDefaultEnrolType: true,
    }
  },
  async mounted() {
    this.loadAllLanguages()
    await this.changeMembership()
  },
  methods: {
    ...mapMutations({
      processingStart: 'PROCESSING_STARTED',
      processingFinished: 'PROCESSING_FINISHED',
    }),
    ...mapActions([
      'loadCountries',
      'loadLanguages',
      'guestLogin',
      'loadAllLanguages',
      'loadMasterDataKeysEnrolment',
      'updateSelectedLanguage',
      'removeError',
      'clearLoadedData',
      'clearShoppingData',
    ]),
    ...mapActions('enrolment', [
      'getEnrolmentsTypes',
      'setEnrolCountryId',
      'getEnrolmentData',
      'updateEnrolmentLanguage',
      'getDynamicRecurringInfo',
      'getDynamicPayeeInfo',
    ]),
    ...mapActions('eshop', ['clearCart', 'loadCart', 'getCartPreservationStatus']),
    async changeMembership() {
      this.loadingMembershipData = true
      this.foundEvoDefaultEnrolType = true
      this.enrolmentData.enrolment_type = ''
      let isEkSmart = 0
      if (this.enrolmentData.membershipType === 'EK Smart') {
        isEkSmart = 1
      } else {
        isEkSmart = 0
      }
      let self = this
      let defaultEnrolTypeID = 1
      let postVars = { is_ek_smart: isEkSmart }

      await self.loadCountries(postVars).then(() => {
        // Set default value
        if (self.countriesOptions.length > 0) {
          if (self.enrolmentData.region === null) {
            this.afterLoading('loadingGeoCountry').then(process => {
              // Set the country to logged in user's country or first country from the list
              // when geo country is not available
              let loggedInUserCountryId = self.$helpers.getValue(self.getLoggedInUser, 'country_id', false)
              let defaultCountry = self.countriesOptions[0]
              if (loggedInUserCountryId) {
                defaultCountry =
                  self.countriesOptions.find(country => country.value === loggedInUserCountryId) ||
                  self.countriesOptions[0]
              }
              self.enrolmentData.region =
                self.countriesOptions.find(country => country.value === self.getDefaultPreferredGeoCountry.id) ||
                defaultCountry
            })

            if (this.$helpers.getValue(self.enrolmentData, 'region.value')) {
              self.loadMasterDataKeysEnrolment({
                country_id: self.enrolmentData.region.value,
                keys: ['sale_types', 'product_additional_requirements'],
              })
            }
          }
        }
      })

      // Reset Country if Selected Country is a Not Applicable Country
      let isValidEnrolCountry = self.countriesOptions.filter(
        country => country.value === self.enrolmentData.region.value
      ).length
      if (!isValidEnrolCountry) {
        // Reset Selected Country to the 1st applicable country
        self.enrolmentData.region = self.countriesOptions[0]
      }
      await self.loadLanguages({ country_id: this.$helpers.getValue(self.enrolmentData, 'region.value') }).then(() => {
        // Set default value
        if (self.languagesOptions.length > 0) {
          if (self.enrolmentData.language === null) {
            let lang = JSON.parse(localStorage.getItem(SELECTED_LANGUAGE))

            this.afterLoading('loadingGeoCountry').then(process => {
              // Set default language based on country if user have not selected a language
              if (lang !== undefined && lang !== null && lang.id !== undefined) {
                self.enrolmentData.language =
                  self.languagesOptions.find(language => language.value === lang.id) || self.languagesOptions[0]
              } else {
                self.enrolmentData.language =
                  self.languagesOptions.find(language => language.value === self.getDefaultPreferredGeoLanguage.id) ||
                  self.languagesOptions[0]
              }

              self.updateEnrolmentLanguage(self.enrolmentData.language)
            })
          } else {
            self.updateEnrolmentLanguage(self.enrolmentData.language)
          }
        }
      })

      this.$nextTick(() => {
        self.enrolmentData.member_data.details.nationality_id = self.enrolmentData.region.value
      })

      let query = {
        country_id: this.$helpers.getValue(self.enrolmentData, 'region.value'),
        is_ek_smart: isEkSmart,
      }
      await self.getEnrolmentsTypes(query).then(async () => {
        let baEnrolType = self.enrolmentTypes.find(type => type.title && type.title.toLowerCase() === 'ba') || {}
        if (self.isEvo) {
          if (baEnrolType.id) {
            await self.setEnrolmentType(baEnrolType.id)
          } else {
            this.foundEvoDefaultEnrolType = false
          }
        } else if (self.enrolmentTypes.length === 1) {
          await self.setEnrolmentType(self.enrolmentTypes[0].id)
        }

        if (Object.keys(self.getUpgradeDetails).length > 0) {
          if (self.enrolment_types.length > 0) {
            defaultEnrolTypeID = self.enrolment_types.find(x => x.title === 'BA' || 'ba').id
          }
          await self.setEnrolmentType(defaultEnrolTypeID)
          await self.nextAction()
        }
      })
      self.setEnrolCountryId(query)
      if (this.getCartPreservationStatus) {
        this.validateRoutes = true
      } else {
        await self.clearCart()
      }
      this.loadingMembershipData = false
    },
    async countryManipulation() {
      let self = this
      if (self.enrolmentData.member_data.details.nationality_id !== self.enrolmentData.region.value) {
        await this.clearShoppingData()
        await this.clearLoadedData(['products-load'])
      }
      self.enrolmentData.member_data.details.nationality_id = self.enrolmentData.region.value

      let defaultEnrolTypeID = 1
      var isEkSmart = 0
      if (this.enrolmentData.membershipType === 'EK Smart') {
        isEkSmart = 1
      } else {
        isEkSmart = 0
      }
      let query = {
        country_id: self.enrolmentData.region.value,
        is_ek_smart: isEkSmart,
      }
      await self.getEnrolmentsTypes(query).then(async () => {
        if (Object.keys(self.getUpgradeDetails).length > 0) {
          if (self.enrolment_types.length > 0) {
            defaultEnrolTypeID = self.enrolment_types.find(x => x.title === 'BA' || 'ba').id
          }
          await self.setEnrolmentType(defaultEnrolTypeID)
          await self.nextAction()
        }
      })
      self.setEnrolCountryId(query)
      self.loadLanguages({ country_id: this.enrolmentData.region.value }).then(() => {
        // Set default value
        if (self.languagesOptions.length > 0) {
          if (self.enrolmentData.language === null) {
            let lang = JSON.parse(localStorage.getItem(SELECTED_LANGUAGE))
            if (lang !== undefined && lang !== null && lang.id !== undefined) {
              self.enrolmentData.language =
                self.languagesOptions.find(language => language.value === lang.id) || self.languagesOptions[0]
              self.updateEnrolmentLanguage(self.enrolmentData.language)
            } else {
              self.enrolmentData.language = self.languagesOptions[0]
            }
          } else {
            let isLanguageExists = self.languagesOptions.find(
              language => language.value === self.enrolmentData.language.value
            )

            if (!isLanguageExists) {
              self.enrolmentData.language = self.languagesOptions[0]
              self.updateEnrolmentLanguage(self.enrolmentData.language)
            }
          }
        }
      })
    },
    resumeEnrolment() {
      if (this.enrolmentResumeCode !== '') {
        this.getEnrolmentData({ sms_code: this.enrolmentResumeCode }).then(() => {
          this.applyTempEnrolmentData().then(() => {
            let query = '?medium=enrolment&code=' + this.getTempSmsCode
            this.guestLogin(query).then(() => {
              this.processingFinished('applyTempEnrolmentData')
              this.$refs.resumeEnrolmentModel.hide()
            })
          })
        })
      }
    },
    async setEnrolmentType(id) {
      this.enrolmentData.enrolment_type = id
      this.enrolmentData.step_states['review-order'] = false
      this.enrolmentData.step_states['checkout'] = false
    },

    controlInputs(name) {
      if (name === 'withoutSponsor') {
        this.enrolmentData.sponsor_name = ''
        this.enrolmentData.sponsor_member_id = ''
        this.enrolmentData.sponsor_user_id = ''
      }
    },
    async continueNext() {
      this.$validator.validateAll().then(async valid => {
        if (
          this.enrolmentData.enrolment_type === '' ||
          (this.enrolmentData.without_sponsor === 0 && this.enrolmentData.sponsor_member_id === '')
        ) {
          if (this.enrolmentData.enrolment_type === '') {
            this.highlightTypes = true
          }
          if (this.enrolmentData.without_sponsor === 0 && this.enrolmentData.sponsor_member_id === '') {
            this.highlightSponsor = true
          }
          let self = this
          window.setTimeout(() => {
            self.highlightTypes = false
            self.highlightSponsor = false
          }, 2000)
        } else {
          if (valid || this.enrolmentData.without_sponsor !== 0 || this.enrolmentData.sponsor_member_id !== '') {
            this.enrolmentData.step_states.start = true
            await this.nextAction()
          } else {
            this.enrolmentData.step_states.start = false
          }
        }
      })
    },
    languageManipulation() {
      this.updateEnrolmentLanguage(this.enrolmentData.language)
    },
    clearDontKnowSponsor(value) {
      if (value) {
        this.enrolmentData.without_sponsor = 0
      }
    },
    getEnrolmentRankTitle(rank) {
      rank = (rank || '').toLowerCase()
      return (
        (rank === 'ba' && this.$t('Common.Terminology.Rank.Ba')) ||
        (rank === 'preferred customer' && this.$t('Common.Terminology.Rank.PreferredCustomer')) ||
        ''
      )
    },
    getEnrolmentInfo(rank) {
      rank = (rank || '').toLowerCase()

      return (
        (rank === 'ba' && this.$t('Enrolment.TypeInfo.BA')) ||
        (rank === 'preferred customer' && this.$t('Enrolment.TypeInfo.PreferredCustomer')) ||
        ''
      )
    },
  },
  watch: {
    enrolmentData() {
      this.highlightTypes = false
      this.highlightSponsor = false
    },
    getEnrolmentLanguage() {
      this.loadCountries({ is_ek_smart: Number(this.enrolmentData.membershipType === 'EK Smart') })
    },
  },
}
</script>
