<template>
  <div class="sponsor-input">
    <b-input-group id="search-sponsor-area" @keyup.enter="searchMember()">
      <b-input-group-prepend
        v-if="enrolmentData.sponsor_member_id"
        class="d-none d-lg-flex align-items-center px-3 m-0 border-right bg-gray-200"
      >
        <span>{{ enrolmentData.sponsor_member_id.toString() }}</span>
      </b-input-group-prepend>
      <b-form-input
        trim
        name="sponsorName"
        v-model="currentSponsorName"
        :disabled="enrolmentData.without_sponsor === 1 || disabled"
        :placeholder="$t('Enrolment.Form.EnterIboIdOrName')"
        v-validate="sponsorRequired ? 'required' : ''"
        class="border-0"
      />
      <b-input-group-prepend v-if="showActionButton || !disabled">
        <b-button
          class="border-y-0 border-right-0"
          @click="searchMember()"
          :disabled="isLoading('getMember')"
          :variant="enrolmentData.without_sponsor === 1 || disabled ? 'outline-light' : 'primary'"
        >
          <b-spinner v-if="isLoading('getMember')" small />
          <icon name="clear-icon" v-else-if="disabled" />
          <icon name="add-icon" v-else-if="enrolmentData.without_sponsor === 1" />
          <icon name="search" class="text-white" v-else />
        </b-button>
      </b-input-group-prepend>
    </b-input-group>
    <sponsor-selection-modal
      ref="sponsorSelectorModal"
      :sponsor-list="getSponsorListing"
      @resetSponsor="resetSponsorField"
    />
  </div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
import SponsorSelectionModal from '@/app/enrolment/_global/components/elements/SponsorSelectionModal'

export default {
  name: 'SearchSponsorInputGroup',
  components: { SponsorSelectionModal },
  props: {
    enrolmentData: {
      type: Object,
      required: true,
    },
    resetErrorName: {
      type: String,
    },
    sponsorRequired: {
      type: Boolean,
      default: false,
    },
    showActionButton: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      currentSponsorName: '',
      disabled: false,
    }
  },
  watch: {
    getSponsorDetails: {
      handler() {
        this.$emit('sponsorChanged', true)
        if (!this.$helpers.isEmpty(this.getSponsorDetails, 'user_id')) {
          if (this.getSponsorListing.length > 1) {
            // If multiple sponsor found
            this.$refs.sponsorSelectorModal.show()
          } else {
            this.enrolmentData.sponsor_member_id = this.getSponsorDetails.member_id
            this.enrolmentData.sponsor_name = this.getSponsorDetails.name
            // TODO: Due to bootstrap issue, we set a timeout function here to reassign the value back to v-model
            setTimeout(() => {
              this.currentSponsorName = this.getSponsorDetails.name
            }, 10)
            this.enrolmentData.sponsor_user_id = this.getSponsorDetails.user_id
            if (
              !this.$helpers.isEmpty(this.getSponsorDetails.user_id) &&
              !this.$helpers.isEmpty(this.getSponsorDetails.member_id)
            ) {
              this.disabled = true
            }
          }
        } else {
          this.enrolmentData.sponsor_member_id = ''
          if (this.$helpers.getValue(this.getSponsorDetails, 'is_empty')) {
            this.$swal({
              title: 'Attention !!',
              text: this.$t('Enrolment.MemberError.Info'),
              type: 'error',
              timer: '5000',
              confirmButtonClass: 'outline-primary',
            })
            if (this.disabled) {
              this.currentSponsorName = ''
              this.disabled = false
            }
          } else {
            this.enrolmentData.sponsor_name = ''
            this.enrolmentData.sponsor_user_id = ''
            this.enrolmentData.global = 1
          }
        }
      },
      deep: true,
    },
    'enrolmentData.without_sponsor'(to) {
      if (to === 1) {
        this.currentSponsorName = ''
        this.resetMemberSponsor()
      }
    },
  },
  computed: {
    ...mapGetters({
      isLoading: 'isLoading',
    }),
    ...mapGetters('enrolment', {
      getSponsorDetails: 'getSponsorDetails',
      getSponsorListing: 'getSponsorListing',
    }),
  },
  mounted() {
    if (this.enrolmentData.sponsor_member_id !== '') {
      this.searchMember(this.enrolmentData.sponsor_member_id)
    } else if (this.enrolmentData.sponsor_user_id === '') {
      this.searchMember(this.enrolmentData.sponsor_user_id)
    }
    if (!this.$helpers.isEmpty(this.enrolmentData.sponsor_name)) {
      this.currentSponsorName = this.enrolmentData.sponsor_name
      this.disabled = true
    }
  },
  methods: {
    ...mapActions(['resetError']),
    ...mapActions('enrolment', ['getMember', 'resetMemberSponsor']),
    async searchMember(param) {
      if (this.disabled || this.enrolmentData.without_sponsor === 1) {
        this.resetSponsorField()
      } else {
        if (param === undefined) {
          param = this.currentSponsorName
        }
        if (!this.$helpers.isEmpty(param)) {
          let query = {
            upgradeMember: 0,
            exact_text: param,
            limit: 10,
            minimal: true,
          }
          await this.getMember(query)
          if (
            !this.$helpers.isEmpty(this.getSponsorDetails.user_id) &&
            !this.$helpers.isEmpty(this.getSponsorDetails.member_id)
          ) {
            this.$emit('sponsorChanged', true)
          }
        }
      }
    },
    reset(name) {
      this.resetError(name)
    },
    resetSponsorField() {
      this.currentSponsorName = ''
      this.disabled = false
      this.enrolmentData.sponsor_member_id = ''
      this.enrolmentData.sponsor_name = ''
      this.enrolmentData.sponsor_user_id = ''
      this.$emit('undisabled', true)
      this.$emit('sponsorChanged', true)
      this.resetMemberSponsor()
    },
  },
}
</script>
