<template>
  <div>
    <b-row class="mb-4">
      <b-col cols="12">
        <b-card-title class="text-black">{{ $t('Autoship.BillingCycle') }}</b-card-title>
      </b-col>
      <b-col cols="12" lg="auto">
        <div>
          <b-form-group
            :label="$t('Autoship.BillOn.Label')"
            :label-for="$t('Autoship.BillOn.Label')"
            class="required mb-2"
          >
            <custom-date-picker
              name="BillOnDate"
              :data-vv-as="$t('Autoship.BillOn.Label')"
              v-model="billOnDate"
              v-validate="'required'"
              :disable-date-range="disableDateRange"
              :has-error="errors.has('BillOnDate')"
              data-qa="autoship-payment-bill-on-date-select"
            />
          </b-form-group>
          <span v-show="errors.has('BillOnDate')" class="text-danger text-nowrap">
            {{ errors.first('BillOnDate') }}
          </span>
        </div>
      </b-col>
    </b-row>
    <b-row class="mb-4">
      <b-col cols="12">
        <b-card-title class="text-black">{{ $t('Common.Payment.CreditCard') }}</b-card-title>
        <b-card-sub-title class="mb-3">{{ $t('Common.Payment.CreditCard.BankInfoWarning') }}</b-card-sub-title>
      </b-col>
      <b-col cols="12" lg="6" v-if="getCardList.length > 0">
        <div>
          <b-form-group
            :label="$t('Common.Payment.CreditCard')"
            :label-for="$t('Autoship.PaymentMethod.Label')"
            class="required mb-2"
          >
            <b-form-select
              name="PaymentMethod"
              :data-vv-as="$t('Common.Payment.CreditCard')"
              :options="getCardList"
              v-model="selectedCreditCard"
              v-validate="'required'"
              :class="{ 'border-danger': errors.has('PaymentMethod') }"
              data-qa="autoship-payment-credit-card-select"
            />
          </b-form-group>
          <div class="pt-1" v-if="errors.has('PaymentMethod')">
            <span class="text-danger text-nowrap">
              {{ errors.first('PaymentMethod') }}
            </span>
          </div>
          <b-button
            variant="link"
            class="px-0 text-decoration-none"
            :class="{ 'float-right': getCardList.length >= 1 }"
            @click="addNewCard = !addNewCard"
            data-qa="autoship-payment-add-new-payment-method-btn"
          >
            {{ $t('Common.Payment.AddNewCreditCard') }}
          </b-button>
        </div>
      </b-col>
      <b-col cols="12" v-if="addNewCard" class="no-overflow" :class="{ 'mt-2': getCardList.length > 0 }">
        <b-col cols="12" lg="6">
          <add-new-card v-model="newCardInfo" :cross-country-banking="true" :card-type-selecting-option="false" />
          <b-row>
            <b-col cols="12">
              <div class="float-right mb-3">
                <b-button
                  variant="link"
                  class="text-black-50 text-decoration-none pr-3"
                  @click="hideAddCard"
                  :class="{ 'd-none': getCardList.length < 1 }"
                  data-qa="add-new-card-cancel-btn"
                >
                  {{ $t('Common.Cancel') }}
                </b-button>
                <b-button variant="primary" @click="SubmitNewCard" data-qa="add-new-card-submit-btn">{{
                  $t('Common.Confirm')
                }}</b-button>
              </div>
            </b-col>
          </b-row>
        </b-col>
      </b-col>
    </b-row>
    <b-row align-h="end">
      <b-col cols="auto" v-if="isUpdate">
        <b-button variant="outline-light" class="ml-3 px-4" @click="initializeUpdateForm()">
          {{ $t('Common.Reset') }}
        </b-button>
        <b-button variant="primary" class="ml-3 px-4" @click="updateSubscriptionDetails()" :disabled="isClean">
          {{ $t('Common.SaveChanges') }}
        </b-button>
      </b-col>
    </b-row>
  </div>
</template>

<script>
import CustomDatePicker from '@/elements/common/components/CustomDatePicker'
import { mapGetters, mapActions } from 'vuex'
import _ from 'lodash'
import AddNewCard from '@/app/_global/components/elements/AddNewCard'
import moment from 'moment'

export default {
  name: 'Payment',
  components: { AddNewCard, CustomDatePicker },
  props: ['isUpdate', 'currentSubscription'],
  data() {
    return {
      disableDateRange: { to: new Date(Date.now()) },
      localCurrentSubscription: {},
      billOnDate: '',
      billingCycle: { value: 1, text: 'Monthly' },
      selectedCreditCard: null,
      newCardInfo: {},
      addNewCard: false,
    }
  },
  async mounted() {
    await this.setDateRangeConfig()
    this.loadFormData()
    if (this.isUpdate) {
      this.localCurrentSubscription = this.currentSubscription
      this.initializeUpdateForm()
    }
  },
  computed: {
    ...mapGetters([
      'getCardList',
      'getAppLocationCountry',
      'getShippingCycleDetail',
      'getPaymentInfo',
      'getMemberDetails',
      'getBackendSetting',
    ]),
    isClean() {
      return (
        this.currentSubscription.next_bill_date === this.billOnDate &&
        this.currentSubscription.card.card_id === this.selectedCreditCard.card_id
      )
    },
  },
  $_veeValidate: {
    validator: 'new',
  },
  methods: {
    ...mapActions([
      'loadCardList',
      'addCard',
      'setPaymentInfoFormData',
      'updateAutoshipSubscription',
      'loadBackendSetting',
    ]),
    loadFormData() {
      if (!_.isEmpty(this.getShippingCycleDetail)) {
        this.billOnDate = _.cloneDeep(this.getShippingCycleDetail.billOn)
        this.billingCycle = _.cloneDeep(this.getShippingCycleDetail.billingCycle)
      }

      if (!_.isEmpty(this.getPaymentInfo)) {
        this.selectedCreditCard = _.cloneDeep(this.getPaymentInfo)
      } else {
        this.loadCardList().then(() => {
          if (this.getCardList.length <= 0) {
            this.addNewCard = true
          }
        })
      }
    },
    hideAddCard() {
      this.addNewCard = false
    },
    SubmitNewCard() {
      this.newCardInfo.user_id = this.getMemberDetails.user_id

      this.$validator.validate('addCardForm.*').then(valid => {
        if (valid) {
          this.addCard(this.newCardInfo).then(response => {
            if (response.data !== undefined) {
              this.loadCardList().then(() => {
                this.selectedCreditCard = response.data
              })
              this.$swal({
                title: this.$t('Card.Add.Success.Title'),
                type: 'success',
                timer: '2100',
                showConfirmButton: false,
              })
              this.addNewCard = false
            } else {
              this.$swal({
                title: this.$t('Card.Add.Fail.Title'),
                text: this.$t('Card.Add.Fail.Msg'),
                type: 'error',
              })
            }
          })
        }
      })
    },
    validateAndSubmit() {
      return this.$validator.validateAll().then(valid => {
        if (valid && this.selectedCreditCard !== null) {
          let payload = {
            shipCycle: { billOnDate: this.billOnDate, billingCycle: this.billingCycle },
            paymentInfo: this.selectedCreditCard,
          }
          this.setPaymentInfoFormData(payload)
          return valid
        } else {
          this.$validator.validate('addCardForm.*')
          this.$validator.validateAll()
          return false
        }
      })
    },
    updateSubscriptionDetails() {
      this.$validator.validateAll().then(valid => {
        if (valid) {
          let payload = {
            user_id: this.getMemberDetails.user_id,
            updated_by_application_user_id: this.getMemberDetails.user_id,
            country_code: this.localCurrentSubscription.country_code,
            subscription_id: this.localCurrentSubscription.subscription_id,
            card_id: this.selectedCreditCard.card_id,
            next_bill_date: this.billOnDate,
          }

          this.updateAutoshipSubscription(payload).then(async response => {
            if (response.data !== undefined) {
              this.$router.push({ name: 'AutoshipDetail' })
              await this.$swal({
                title: this.$t('Autoship.Edit.SavedSuccess'),
                type: 'success',
                timer: '2100',
                showConfirmButton: false,
              })
            } else {
              await this.$swal({
                title: this.$t('Autoship.Edit.SavedFail'),
                text: this.$t('Common.Error.ActionFailure.HelpText'),
                type: 'error',
              })
            }
          })
        } else {
          this.$swal({
            title: this.$t('Common.Error.RequiredField'),
            type: 'error',
          })
        }
      })
    },
    initializeUpdateForm() {
      this.billOnDate = this.localCurrentSubscription.next_bill_date
      this.selectedCreditCard = {
        user_id: this.getMemberDetails.user_id,
        ...this.localCurrentSubscription.card,
      }
    },
    async setDateRangeConfig() {
      let disableMeta = { to: new Date(Date.now()) }
      await this.loadBackendSetting(['autoship_next_billing_date_range', 'autoship_unavailable_billing_date'])

      let autoshipDateRangeConfig = this.getBackendSetting('autoship_next_billing_date_range') || {}
      let autoshipDisabledDate = this.getBackendSetting('autoship_unavailable_billing_date') || {}

      if (typeof autoshipDateRangeConfig.data == 'number')
        disableMeta['from'] = moment()
          .add(autoshipDateRangeConfig.data, 'days')
          .toDate()

      if (Array.isArray(autoshipDisabledDate.data)) {
        disableMeta['daysOfMonth'] = autoshipDisabledDate.data
      }

      this.disableDateRange = disableMeta
    },
  },
}
</script>
