import { mapActions, mapGetters } from 'vuex'
import {
  ESHOP_CHECKOUT,
  ESHOP_CHECKOUT_SELECT_SIZES,
  ESHOP_LISTING,
  ESHOP_RECURRING_INFO,
  ESHOP_ORDER_REVIEW,
  ESHOP_ORDER_FOC_PWP,
  ESHOP_I_TOKEN_REDEEM,
  ESHOP_ORDER_PAYMENT,
  ESHOP_ORDER_COMPLETE,
} from '@/config/url-prefix'
import validatedRouteMixin from '@/app/_global/mixins/validatedRouteMixin'
import { iconByName } from '@/app/_global/fixtures/eshop-order-default-icons'

export default {
  mixins: [validatedRouteMixin],
  data() {
    let self = this
    return {
      routingOrder: [
        {
          path: ESHOP_LISTING,
          previous: this.$t('Eshop.PreCheckout.Listing.Previous'),
          icon: iconByName('review'),
          title: this.$t('Common.CheckoutSteps.SelectProduct'),
          validate: () => {
            return (
              self.$route.query.redirect === 'true' ||
              Promise.resolve(self.getCartTotal > 0 && self.getCheckout.status === true)
            )
          },
        },
        {
          path: ESHOP_I_TOKEN_REDEEM,
          icon: 'sidebar-i-token',
          title: this.$t('Itoken.Redemption.Title'),
          addCallback: () => {
            let redemptionKey = self.$helpers.getValue(self.getCartCampaignDetails, 'redemption_method.key')
            return redemptionKey === 'both' || redemptionKey === 'on_the_spot'
          },
          previous: this.$t('Eshop.PreCheckout.Redemption.Previous'),
          next: this.$t('Itoken.Redemption.Title'),
        },
        {
          path: ESHOP_CHECKOUT_SELECT_SIZES,
          routeName: 'CheckoutSelectSizes',
          get previous() {
            return self.getCartNeedSizeSelection === true
              ? self.$t('Eshop.PreCheckout.CheckoutSelectSizes.Previous')
              : self.$t('Eshop.PreCheckout.CheckoutInstallationDetails.Previous')
          },
          next: this.$t('Eshop.PreCheckout.CheckoutSelectSizes.Next'),
          addCallback: self.cartNeedSelection,
          validate: async () => {
            if (self.$route.query.redirect === 'true') {
              return true
            }
            if (self.getCartNeedAddressSelection === true) {
              //Checks if the product installation details is valid
              if ((await self.isInstallationDetailsValid()) === false) {
                self.logError({ cartError: self.$t('Eshop.InstSelection.Invalid') })
                return Promise.resolve(false)
              } else {
                return Promise.resolve(true)
              }
            } else if (self.getCartNeedSizeSelection === true) {
              //Check if the dummy product have size selection
              if ((await self.checkCartDummyAllSizesSelected()) === false) {
                self.logError({ cartError: self.$t('Eshop.SizeSelection.PleaseSelect') })
                return Promise.resolve(false)
              } else {
                return Promise.resolve(true)
              }
            } else {
              return Promise.resolve(true)
            }
          },
          icon: 'eshop-select-size',
          title: this.$t('Eshop.SizeSelection.Step.Title'),
        },
        {
          path: ESHOP_RECURRING_INFO,
          previous: this.$t('Eshop.PreCheckout.RecurringInfo.Previous'),
          next: this.$t('Eshop.PreCheckout.RecurringInfo.Next'),
          icon: 'eshop-recurring',
          title: this.$t('Eshop.RecurringInfo.Step.Title'),
          validate: async () => self.$route.query.redirect === 'true' || (await this.isValidCardInfoFields()),
          addCallback: () => Promise.resolve(this.getCartHasRental),
        },
        {
          path: ESHOP_ORDER_FOC_PWP,
          previous: this.$t('Eshop.PreCheckout.OrderFocPwp.Previous'),
          next: this.$t('Eshop.PreCheckout.OrderFocPwp.Next'),
          addCallback: async () => {
            if (this.getPwpFocSelectionComplete !== true) {
              await this.loadCartProductEligible()
            }
            return this.getEligiblePromotion.length > 0
          },
          validate: async () =>
            self.$route.query.redirect === 'true' ||
            self.getEligiblePromotion.length === 0 ||
            self.getPwpFocSelectionComplete === true,
          icon: 'eshop-prize',
          title: this.$t('Eshop.Order.FocPwp.Step.Title'),
        },
        {
          path: ESHOP_ORDER_REVIEW,
          next: this.$t('Eshop.PreCheckout.OrderReview.Next'),
          icon: 'eshop-shipping',
          title: this.$t('Eshop.Order.Review.Step.Title'),
          validate: async () =>
            self.$route.query.redirect === 'true' ||
            (self.getOrderShipping !== null && self.getOrderShipping.validated === true),
        },
        {
          path: ESHOP_ORDER_PAYMENT,
          next: this.$t('Eshop.PreCheckout.OrderReview.Next'),
          icon: iconByName('payment'),
          title: this.$t('Common.MakePayment'),
          validate: () => self.getPaymentStepStatus.validated === true || self.$route.query.redirect === 'true',
        },
        {
          path: ESHOP_ORDER_COMPLETE,
          next: this.$t('Eshop.PreCheckout.OrderReview.Next'),
          icon: iconByName('completed'),
          title: this.$t('Eshop.Order.Completed.Text'),
        },
      ],
    }
  },
  methods: {
    ...mapActions(['logError', 'loadMasterDataKeysEnrolment']),
    ...mapActions('eshop', [
      'cartNeedSelection',
      'loadCartProductEligible',
      'loadCart',
      'checkCartDummyAllSizesSelected',
      'loadCartSizesDetails',
      'isInstallationDetailsValid',
    ]),
    ...mapActions('enrolment', ['isValidCardInfoFields']),
    async initPreCheckoutRoute() {
      await this.loadCart()

      await this.loadMasterDataKeysEnrolment({
        keys: ['sale_types', 'product_additional_requirements'],
      }).then(async () => {})

      if (this.$route.path === ESHOP_CHECKOUT) {
        // move to next page from checkout page
        await this.initRouting(false)
        // bypass validation
        this.validateRoutes = false
        try {
          this.$router.replace(this.selectedOrder[1].path)
        } catch (e) {
          // eslint-disable-next-line no-console
          console.error(e)
        }
      } else {
        this.validateRoutes = true
        await this.initRouting(true)
      }
    },
  },
  mounted() {},
  computed: {
    ...mapGetters('eshop', [
      'getEligiblePromotion',
      'getOrderShipping',
      'getCartTotal',
      'getCheckout',
      'getPwpFocSelectionComplete',
      'getCartNeedAddressSelection',
      'getCartNeedSizeSelection',
      'getCartHasRental',
      'getPaymentStepStatus',
      'getCartCampaignDetails',
      'getRedeemLaterStatus',
      'getITokenCartItems',
    ]),
  },
}
