<template>
  <modal-template size="xl" is-footer-hide is-header-show>
    <template v-slot:header>
      <div class="w-100">
        <div class="float-right">
          <b-button variant="outline-primary" @click="hide">
            <icon name="eshop-angle-close" />
            <span class="pl-1">{{ $t('Common.Close') }}</span>
          </b-button>
        </div>
      </div>
    </template>

    <template v-slot:body>
      <b-container class="product-previewer">
        <b-row>
          <b-col cols="12" lg="3" class="mb-4">
            <b-img fluid :src="getProductImage" />
          </b-col>

          <b-col cols="12" lg="9">
            <div>
              <div>
                <h4 class="text-capitalize mb-3">{{ getProductName }}</h4>
              </div>

              <div class="text-muted mb-1">
                <span class="pr-2">{{ getProductDetails.sku }}</span>
                <b-badge v-if="getProductDetails.has_fpp" variant="primary" class="p-2">
                  {{ $t('Eshop.Product.FPP') }}
                </b-badge>
                <b-badge v-if="getProductDetails.has_amp" variant="amp" class="p-2">
                  {{ $t('Eshop.Product.AMP') }}
                </b-badge>
              </div>

              <div class="font-weight-bolder mb-3">
                <template v-if="getProductDetails.rental_plan">
                  <div>
                    <span>
                      {{ currency }}
                      {{ getProductDetails.rental_plan.initial_payment }}
                      ({{ $t('Eshop.Product.Initial') }})
                    </span>
                  </div>
                  <div>
                    <span>
                      {{ currency }}
                      {{ getProductDetails.rental_plan.monthly_repayment }} x
                      {{ getProductDetails.rental_plan.month }}
                      {{ $t('Eshop.Product.Tenure') }}
                    </span>
                  </div>
                </template>
                <template v-else>
                  <span>{{ currency }} {{ getProductDetails.price }}</span>
                </template>
              </div>

              <div
                v-if="!getProductDetails.is_starter_kit && getCvBreakDown.length"
                class="d-flex flex-row border-y py-2 mb-3"
              >
                <div v-for="(point, idx) in getCvBreakDown" :key="idx" class="mr-3">
                  <span class="pr-1">{{ point.label }}</span>
                  <span class="text-primary">{{ point.value }}</span>
                </div>
              </div>
            </div>

            <div class="custom-scroll-bar mb-2">
              <div v-if="isLoading('productOrKittingDetails')">
                <b-skeleton width="80%" />
                <b-skeleton width="90%" />
                <b-skeleton width="60%" />
              </div>
              <div v-else class="overflow-y-auto pr-md-2 product-description">
                <div v-if="getProductInformation.length">
                  <template v-for="(content, index) in getProductInformation">
                    <b-card no-body :key="index" class="mb-3">
                      <b-card-header
                        v-b-toggle="`accordion-${index}`"
                        class="outline-none text-capitalize font-weight-bold d-flex align-items-center justify-content-between"
                      >
                        <span>{{ content.title }}</span>
                        <icon name="dashboard-arrow-down" />
                      </b-card-header>
                      <b-collapse :id="`accordion-${index}`" visible>
                        <b-card-body class="p-3" v-html="content.body" />
                      </b-collapse>
                    </b-card>
                  </template>
                </div>

                <div v-else class="mb-3">
                  {{ $t('Eshop.Order.ProductDetail.NoDescription') }}
                </div>
              </div>
            </div>

            <div
              v-if="showActionBar && $helpers.getValue(getProductDetails, 'label.allow_checkout', '') !== false"
              class="sticky-bottom"
            >
              <div class="dashboard-panel-element rounded-2">
                <b-row class="align-items-center">
                  <b-col cols="12" lg="6" class="mb-3 mb-lg-0">
                    <b-row class="align-items-center">
                      <b-col cols="auto" class="font-size-6 font-weight-bolder text-muted font-italic">
                        {{ $t('Common.Quantity') }} :
                      </b-col>
                      <b-col>
                        <quantity-selector
                          :min-range="0"
                          :value="getCartCurrentProductQuantity"
                          :quantity-buttons-wrapper-class="[
                            'order-2',
                            'px-2',
                            { 'd-none': getProductDetails.is_rental || getProductDetails.is_starter_kit },
                          ]"
                          :max-range="getProductDetails.is_rental || getProductDetails.is_starter_kit ? 1 : 999"
                          @input="setProductQuantity"
                          :data-qa-prefix="dataQaPrefix"
                        />
                      </b-col>
                    </b-row>
                  </b-col>
                  <b-col cols="12" lg="6">
                    <div v-if="getProductDetails.is_rental || getProductDetails.is_starter_kit">
                      <eshop-product-quantity-selector
                        :max-range="1"
                        @update="addToCart"
                        :is-rental="getProductDetails.is_rental"
                        :quantity="getCartCurrentProductQuantity"
                        :add-to-cart-btn-text="
                          (getProductDetails.is_starter_kit && $t('Eshop.Order.GlobalWords.Select')) || ''
                        "
                        :data-qa-prefix="dataQaPrefix"
                        ref="eshopProductQuantitySelector"
                      />
                    </div>
                    <div v-else>
                      <b-button
                        v-if="getCartCurrentProductQuantity > 0 && getLocalProductQuantity === 0"
                        block
                        variant="outline-medium"
                        @click="addToCart(0)"
                      >
                        {{ $t('Enrolment.Remove.Label') }}
                      </b-button>
                      <b-button
                        v-else
                        block
                        variant="primary"
                        @click="addToCart()"
                        :disabled="getLocalProductQuantity === getCartCurrentProductQuantity"
                      >
                        {{ $t('Eshop.AddToCart.Label') }}
                      </b-button>
                    </div>
                  </b-col>
                </b-row>
              </div>
            </div>
          </b-col>
        </b-row>
      </b-container>
    </template>
  </modal-template>
</template>

<script>
import currencyMixin from '@/app/_global/mixins/currencyMixin'
import ModalTemplate from '@/elements/common/components/modalTemplate'
import ImagePlaceholder from '@/assets/img/image-placeholder-with-frame.svg'
import { mapActions, mapGetters } from 'vuex'
import QuantitySelector from '@/app/_global/components/blocks/QuantitySelector'
import EshopProductQuantitySelector from '@/app/_global/components/blocks/EshopProductQuantitySelector'

export default {
  name: 'ProductDetailsPreviewerPopup',
  mixins: [currencyMixin],
  components: { EshopProductQuantitySelector, QuantitySelector, ModalTemplate },
  props: {
    showBv: { type: Boolean, default: true },
    showAmpCv: { type: Boolean, default: true },
    showRnkCv: { type: Boolean, default: true },
    showWpCv: { type: Boolean, default: true },
    addProductCallBack: { type: Function },
    showActionBar: { type: Boolean, default: true },
  },
  data() {
    return {
      quantity: null,
      productDetails: {},
      dataQaPrefix: 'productDetailsPreviewer',
    }
  },
  computed: {
    ...mapGetters(['getSelectedLanguage', 'getAppLocationCountry', 'isLoading']),
    ...mapGetters('eshop', ['getCartProductQuantity']),
    getProductDetails() {
      return this.productDetails || {}
    },
    getProductImage() {
      let image = this.getProductDetails.image || ImagePlaceholder
      return this.$appSettings.config.https ? image.replace('http:', 'https:') : image
    },
    getProductName() {
      return (this.getProductDetails.name || '').toLowerCase()
    },
    getCvBreakDown() {
      let { amp, eligible, upgrade, welcome_pack, sv, cbp_point } = this.getProductDetails.unit_cv || {}

      if (this.$appSettings.evo.enable) {
        return [
          { label: this.$t('Common.Terminology.Bv'), value: eligible || '0.00' },
          { label: this.$t('Common.Terminology.Sv'), value: sv || '0.00' },
          { label: this.$t('Common.Terminology.Cbp'), value: cbp_point || '0.0000' },
        ]
      }
      return [
        {
          label: this.$t('Common.Terminology.Bv'),
          value: eligible || 0,
          show: this.showBv,
        },
        {
          label: this.$t('Common.Terminology.AmpCv'),
          value: amp || 0,
          show: this.showAmpCv,
        },
        {
          label: this.$t('Common.Terminology.RnkCv'),
          value: upgrade || 0,
          show: this.showRnkCv,
        },
        {
          label: this.$t('Common.Terminology.WpCv'),
          value: welcome_pack || 0,
          show: this.showWpCv,
        },
      ].filter(cv => cv.show !== false && cv.value)
    },
    getProductInformation() {
      let descriptions = this.getProductDetails.description || []
      if (descriptions.length > 0) {
        let content =
          descriptions.find(info => info.language_id === this.getSelectedLanguage.id || 1) || descriptions[0] || {}

        return [
          { title: this.$t('Eshop.Order.ProductDetail.Benefits'), body: content.benefits },
          { title: this.$t('Eshop.Order.ProductDetail.ProductSpecification'), body: content.specification },
          { title: this.$t('Eshop.Order.ProductDetail.Description'), body: content.marketing_description },
        ].filter(info => info.body)
      }
      return []
    },
    getCartCurrentProductQuantity() {
      // retrieve the product quantity return from cart-details
      let { kitting_id, product_id } = this.getProductDetails
      return this.getCartProductQuantity(product_id, kitting_id)
    },
    getLocalProductQuantity() {
      // retrieve the emitted product quantity number in the component
      // * when product cart quantity = 1 during init time, emit event not trigger thus I force return 1 when the local quantity is null
      return this.quantity === null ? 1 : this.quantity
    },
  },
  methods: {
    ...mapActions('eshop', ['loadProductOrKittingDetails']),
    show(data) {
      this.localDataReset()
      if (data) {
        this.productDetails = { ...data }
        this.$bvModal.show('modal')
        this.loadProductDetails()
      }
    },
    hide() {
      this.$bvModal.hide('modal')
    },
    loadProductDetails() {
      // kinda "lazy load" the product description area
      this.loadProductOrKittingDetails({
        product_id: this.getProductDetails.product_id,
        kitting_id: this.getProductDetails.kitting_id,
        country_id: this.getAppLocationCountry.countryId,
        location_id: this.getAppLocationCountry.locationId,
      }).then(result => {
        if (result && result.details) {
          this.productDetails['description'] = [...(result.details.description || [])]
        }
      })
    },
    setProductQuantity(val) {
      this.quantity = val
    },
    addToCart(qty = null) {
      let quantity = qty === null ? this.getLocalProductQuantity : qty

      if (typeof this.addProductCallBack === 'function' && quantity !== null) {
        this.addProductCallBack({
          product_id: this.getProductDetails.product_id,
          kitting_id: this.getProductDetails.kitting_id,
          salesTypeId: this.getProductDetails.sales_type_id,
          quantity,
        })
      }
      this.hide()
    },
    localDataReset() {
      this.quantity = null
      this.productDetails = {}
    },
  },
}
</script>
