<template>
  <div>
    <b-row class="mb-2">
      <b-col>
        <h5 class="text-black-50 mt-0">{{ $t('MyBundle.BundleInfoForm.Title') }}</h5>
      </b-col>
    </b-row>

    <b-row>
      <b-col>
        <b-form-group
          label-for="bundleName"
          :label-class="{ required: !readOnly }"
          :invalid-feedback="errors.first('BundleName')"
          :label="$t('MyBundle.BundleInfoForm.BundleNameField.Label')"
        >
          <!-- Hide error message during read only mode-->
          <b-form-input
            id="bundleName"
            trim
            type="text"
            name="BundleName"
            :readonly="readOnly"
            v-model="localFormData.bundleName"
            v-validate="{ required: !readOnly }"
            :state="!errors.has('BundleName') && null"
            :data-qa="`${dataQaPrefix}-bundleInfoForm-bundleName-input`"
            :data-vv-as="$t('MyBundle.BundleInfoForm.BundleNameField.Label')"
          />
        </b-form-group>

        <b-form-group label-for="bundleDescription" :label="$t('MyBundle.BundleInfoForm.BundleDescriptionField.Label')">
          <b-form-textarea
            id="bundleDescription"
            trim
            rows="8"
            no-resize
            :readonly="readOnly"
            name="BundleDescription"
            v-model="localFormData.bundleDescription"
            :data-qa="`${dataQaPrefix}-bundleInfoForm-bundleDescription-textarea`"
          />
        </b-form-group>
      </b-col>
    </b-row>

    <div class="mb-2">
      <label>{{ $t('MyBundle.BundleInfoForm.ProductChecklist.Label') }}</label>
      <b-table
        show-empty
        :responsive="true"
        :items="bundleItems"
        :fields="getBundleItemsFields"
        class="border-bottom-double border-light-extra mb-0"
      >
        <template v-slot:empty>
          <h5 class="text-center text-danger mt-3">{{ $t('MyBundle.BundleInfoForm.NoProductFound') }}</h5>
        </template>

        <template v-slot:cell(index)="row">
          {{ row.index + 1 }}
        </template>

        <template v-slot:cell(product_prices)="row">
          {{ row.value.gmp_price_tax }}
        </template>
      </b-table>

      <b-table-simple
        v-if="bundleItems.length"
        class="text-right text-primary font-weight-bold border-bottom-double border-light"
      >
        <template v-if="getMemberPriceConfig">
          <b-tr>
            <b-td>
              <b-form-checkbox
                name="MemberPrice"
                :disabled="readOnly"
                class="full-width-checkbox"
                :state="isPriceTypeSelected && null"
                v-model="localFormData.useMemberPrice"
                @change="setBundleCheckoutEnrolmentType"
                :data-qa="`${dataQaPrefix}-bundleInfoForm-memberPrice-checkbox`"
              >
                {{ getMemberPriceConfig.normalized_value }}
              </b-form-checkbox>
            </b-td>

            <b-td :class="{ 'text-black-50': !localFormData.useMemberPrice }">
              <span>{{ getPrice(bundlePrices.member_price || 0) }} *</span>
            </b-td>
          </b-tr>

          <template v-for="(enrolmentType, idx) in bundleCheckoutEnrolmentTypes">
            <b-tr v-show="localFormData.useMemberPrice" :key="idx" class="animated fadeInDown bg-gray-100">
              <b-td colspan="2">
                <div class="d-flex justify-content-end">
                  <span class="pr-3" :class="{ 'text-danger': errors.has(enrolmentType.key) }">
                    {{ enrolmentType.normalized_value }}
                  </span>
                  <b-form-radio
                    class="m-0"
                    :disabled="readOnly"
                    :name="enrolmentType.key"
                    :value="enrolmentType.key"
                    :state="!errors.has(enrolmentType.key) && null"
                    v-model="localFormData.bundleEnrolmentType"
                    v-validate="{ required: !isBundleCheckoutEnrolmentTypeSelected }"
                    :data-qa="`${dataQaPrefix}-bundleInfoForm-enrol-${$helpers.kebabCase(enrolmentType.key)}-radio`"
                  />
                </div>
              </b-td>
            </b-tr>
          </template>
        </template>

        <b-tr v-if="getRetailPriceConfig">
          <td>
            <b-form-checkbox
              name="RetailPrice"
              :disabled="readOnly"
              class="full-width-checkbox"
              :state="isPriceTypeSelected && null"
              v-model="localFormData.useRetailPrice"
              :data-qa="`${dataQaPrefix}-bundleInfoForm-retailPrice-checkbox`"
            >
              {{ getRetailPriceConfig.normalized_value }}
            </b-form-checkbox>
          </td>

          <b-td :class="{ 'text-black-50': !localFormData.useRetailPrice }">
            <span>{{ getPrice(bundlePrices.retail_price || 0) }} *</span>
          </b-td>
        </b-tr>
      </b-table-simple>

      <span v-if="bundleItems.length" class="text-black-50">
        {{ $t('Common.Sales.PreSalesDeclaimer') }}
      </span>
    </div>
  </div>
</template>

<script>
export default {
  name: 'BundleInfoForm',
  props: {
    currency: { type: String, required: true },
    readOnly: { type: Boolean, default: false },
    value: { type: Object, default: () => ({}) },
    dataQaPrefix: { type: String, required: true },
    bundlePrices: { type: Object, required: true },
    bundleItems: { type: Array, default: () => [] },
    bundlePriceOptions: { type: Array, default: () => [] },
    bundleCheckoutEnrolmentTypes: { type: Array, default: () => [] },
  },
  $_veeValidate: {
    validator: 'new',
  },
  data() {
    return {
      localFormData: {
        bundleName: '',
        bundleDescription: '',
        useMemberPrice: null,
        useRetailPrice: null,
        bundleEnrolmentType: null,
      },
    }
  },
  watch: {
    localFormData: {
      handler(data) {
        this.$emit('input', data)
      },
      deep: true,
    },
    bundlePriceOptions(options) {
      if (options.length) {
        // Check if bundle price types still initial ("null") state
        if (this.localFormData.useMemberPrice === null) {
          this.localFormData.useMemberPrice = options.findIndex(config => config.key === 'bundle_member_price') !== -1
          this.setDefaultCheckoutEnrolmentType()
        }

        if (this.localFormData.useRetailPrice === null) {
          this.localFormData.useRetailPrice = options.findIndex(config => config.key === 'bundle_retail_price') !== -1
        }
      }
    },
  },
  computed: {
    getBundleItemsFields() {
      return [
        { key: 'index', label: this.$t('Common.Table.No') },
        { key: 'product_sku', label: this.$t('Common.ProductCode') },
        { key: 'product_name', label: this.$t('Common.Product.ProductName') },
        { key: 'product_quantity', label: this.$t('Common.Quantity'), class: ['text-right'] },
        {
          key: 'product_prices',
          label: this.$t('Eshop.LeftPanel.Price.Title', { currency: this.currency }),
          class: ['text-right'],
        },
      ]
    },
    getMemberPriceConfig() {
      return this.bundlePriceOptions.find(option => option.key === 'bundle_member_price')
    },
    getRetailPriceConfig() {
      return this.bundlePriceOptions.find(option => option.key === 'bundle_retail_price')
    },
    isPriceTypeSelected() {
      let { useMemberPrice, useRetailPrice } = this.localFormData
      return Boolean(this.readOnly || useMemberPrice || useRetailPrice)
    },
    isBundleCheckoutEnrolmentTypeSelected() {
      let { useMemberPrice, bundleEnrolmentType } = this.localFormData
      return this.readOnly || !useMemberPrice || Boolean(bundleEnrolmentType)
    },
  },
  mounted() {
    if (this.value) {
      this.localFormData = { ...this.value }
    }
  },
  methods: {
    getPrice(price) {
      price = price.toString()
      return ['0', '0.00'].includes(price) ? '-' : this.$helpers.getCurrencyValue(price)
    },
    setDefaultCheckoutEnrolmentType() {
      this.localFormData.bundleEnrolmentType = this.$helpers.getValue(
        this.bundleCheckoutEnrolmentTypes,
        '[0].key',
        null
      )
    },
    setBundleCheckoutEnrolmentType(useMemberPrice) {
      if (useMemberPrice) {
        this.setDefaultCheckoutEnrolmentType()
      } else {
        this.localFormData.bundleEnrolmentType = null
      }
    },
  },
}
</script>
