<template>
  <container-md-template
    :is-busy="isLoading(['loadingBundleInfo', 'guest_login']) || bundleDetails.hasOwnProperty('init')"
    :show-not-found="bundleDetails.hasOwnProperty('error')"
  >
    <b-alert
      fade
      dismissible
      variant="danger"
      :show="showCheckoutError"
      @dismissed="showCheckoutError = 0"
      class="border-0 sticky-top rounded-0"
    >
      <h5 class="alert-heading">{{ $t('BundleDetails.Checkout.Fail') }}</h5>
      <p class="m-0">{{ $t('Common.Error.ActionFailure.HelpText') }}</p>
    </b-alert>
    <b-row class="m-0">
      <b-col v-if="bundleDetails.bundle_image" cols="12" lg="5">
        <b-img-lazy
          center
          :rounded="true"
          blank-width="360"
          blank-height="300"
          alt="Bundle Image"
          blank-color="lightgrey"
          :src="bundleDetails.bundle_image"
          class="object-fit-scale-down mw-100 bundle-cover-image"
        />
        <hr class="d-lg-none" />
      </b-col>
      <b-col class="border-lg-left">
        <div>
          <h2 class="text-capitalize">
            {{ bundleDetails.bundle_name }}
          </h2>

          <div v-if="bundleDetails.bundle_total">
            <h5 class="text-secondary">
              <span>{{ $t('Common.Terminology.MemberPrice') }}: </span>
              <span>
                {{ showProductPrice(bundleDetails.bundle_currency_code, bundleDetails.bundle_total.member_price) }}
              </span>
            </h5>
            <h5 class="text-secondary">
              <span>{{ $t('Common.Terminology.RetailPrice') }}: </span>
              <span>
                {{ showProductPrice(bundleDetails.bundle_currency_code, bundleDetails.bundle_total.retail_price) }}
              </span>
            </h5>
            <b-row class="align-items-center mt-4">
              <b-col cols="auto" class="pr-3">
                <span class="font-weight-bold">{{ $t('Common.Quantity') }}: </span>
              </b-col>
              <b-col class="px-0">
                <quantity-selector v-model="bundleOrderQuantity" class="m-0" />
              </b-col>
            </b-row>
          </div>
        </div>

        <div class="mt-4">
          <p>{{ bundleDetails.bundle_description }}</p>
        </div>

        <div class="mt-5" v-if="bundleDetails.bundle_items">
          <h5>{{ $t('BundleDetails.BundleItems.WhatsInTheBundle') }}</h5>
          <div v-for="(product, index) in bundleDetails.bundle_items" :key="index">
            <b-row>
              <b-col cols="auto">
                <b-img-lazy
                  center
                  width="100"
                  height="100"
                  :rounded="true"
                  blank-color="lightgrey"
                  class="object-fit-scale-down"
                  :src="product.product_image || defaultProductPlaceholder"
                />
              </b-col>
              <b-col class="align-self-center">
                <div class="font-weight-bold">{{ product.product_name }}</div>
                <small class="text-black-50">{{ product.product_sku }}</small>
                <div class="font-weight-bold mt-2">x{{ product.product_quantity }}</div>
              </b-col>
            </b-row>
            <hr class="m-2" />
          </div>
        </div>

        <div v-if="bundleDetails.bundle_total" class="my-5 sticky-bottom">
          <b-button
            pill
            block
            size="lg"
            variant="primary"
            @click="checkoutBundle"
            class="text-uppercase sticky-bottom-0 d-flex justify-content-center"
          >
            <span class="mr-2">
              <b-spinner v-show="isLoading('processingBundleCheckout')" small class="align-baseline" />
              <b-icon v-show="!isLoading('processingBundleCheckout')" icon="cart4" class="align-baseline" />
            </span>
            <span class="font-size-5">{{ $t('Common.Sales.PreCheckout') }}</span>
          </b-button>
        </div>
      </b-col>
    </b-row>
  </container-md-template>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import ProductPlaceholder from '@AppCenter/assets/img/product-placeholder.svg'
import ContainerMdTemplate from '@AppCenter/_global/components/templates/ContainerMdTemplate'
import QuantitySelector from '@AppCenter/app/bundle-info-app/_global/components/blocks/QuantitySelector'
export default {
  name: 'ElkenBundleDetails',
  components: { ContainerMdTemplate, QuantitySelector },
  beforeRouteEnter(to, from, next) {
    next(async vm => {
      let query = '?medium=enrolment&referrer='
      await vm.guestLogin(query).then(() => {
        vm.loadBundleInfo()
        next()
      })
    })
  },
  props: {
    bundleSlug: { type: String, required: true },
    id: { type: String, required: true },
  },
  data() {
    return {
      bundleDetails: { init: true },
      bundleOrderQuantity: 1,
      showCheckoutError: 0,
      defaultProductPlaceholder: ProductPlaceholder,
    }
  },
  metaInfo() {
    return {
      title: this.$t('App.Title'),
      meta: [
        { name: 'description', content: this.bundleDetails.bundle_description || '' },
        { property: 'og:type', content: 'article', vmid: 'og:type' },
        { property: 'og:title', content: this.bundleDetails.bundle_name || '', vmid: 'og:title' },
        { property: 'og:image', content: this.bundleDetails.bundle_image || '', vmid: 'og:image' },
      ],
    }
  },
  computed: {
    ...mapGetters(['isLoading']),
  },
  methods: {
    ...mapActions(['guestLogin']),
    ...mapActions('bundleInfoApp', ['getBundleInfo', 'bundleCheckout']),
    loadBundleInfo() {
      let identifier = this.bundleSlug.split('-').slice(-1)[0]
      this.getBundleInfo({ bundleId: this.id, identifier }).then(result => {
        if (result) {
          if (result.bundle_slug !== this.bundleSlug) {
            this.$route.replace({ name: 'BundleDetailsPage', params: { bundleSlug: result.bundle_slug, id: this.id } })
            return
          }
          result.bundle_image = result.bundle_image || this.defaultProductPlaceholder
          result.bundle_name = result.bundle_name || this.$t('BundleDetails.BundleTitle.Placeholder')
        }
        this.bundleDetails = result || { error: true }
      })
    },
    checkoutBundle() {
      let payload = {
        bundleSlug: this.bundleDetails.bundle_slug,
        quantity: parseInt(this.bundleOrderQuantity),
      }
      this.bundleCheckout(payload).then(response => {
        if (response && response.checkout_url) {
          window.open(response.checkout_url, '_self')
        } else {
          this.showCheckoutError = 15 //sec
        }
      })
    },
    showProductPrice(currency, price) {
      return (Number.parseFloat(price) > 0 && `${currency} ${price}`) || '-'
    },
  },
}
</script>
