<script setup>
import { ref, defineProps, defineEmits } from 'vue';
import { Colors } from "@/ThemeConfig.vue";
import { showPopper, popperBoxProductAddonHtml, removePopperIfOpen } from "@/components/displays/PopperDefault.vue";
import Swal from "sweetalert2";
import CustomerProductDiscountDisplay
  from "@/components/displays/department/pos/displays/CustomerProductDiscountDisplay.vue";

const expandIcon = ref(null);

const emit = defineEmits(['add-to-cart']);

const props = defineProps({
  id: Number,
  product: Object,
  name: String,
  description: String,
  price: Number,
  image: String,
  addons: Array,
  isSelected: Boolean,
  selectedAddons: Array,
  toggleProductAddon: Function,
  getProductAddonQuantity: Function,
  addProductAddon: Function,
  subtractProductAddon: Function,
  unselect: Function,
  setProductAddonNote: Function,
  customerDiscounts: Array,
  customerAttributes: Array,
});

const isAddonSelected = (productId, addonId) => {
  return props.selectedAddons.some((addon) => addon.product_id === productId && addon.addon_id === addonId && addon.status === true);
};

const getAddonPrice = (addonId) => {
  const addon = props.addons.find((addon) => addon.id === addonId);
  return addon.product.price;
};

const showAddonPopper = (addon, element) => {
  showPopper(popperBoxProductAddonHtml(
      addon.id,
      addon.name,
      addon.product.price,
      addon.product.description,
      'pos-addon-popper'
  ), element);
};

const hideAddonPopper = (addon) => {
  removePopperIfOpen();
};

const emitAddToCart = (id) => {
  emit('add-to-cart', id);
};

const toggleIsSelected = () => {
  if (props.isSelected)
  {
    props.unselect()
  }
};

const hasRestrictAdditionalServices = () => {
  return props.customerAttributes.some((attribute) => attribute.attribute === 'restrictAdditionalServices');
};

const hasRestrictSpotFree = () => {
  return props.customerAttributes.some((attribute) => attribute.attribute === 'restrictSpotFree');
};

const hasRestrictInteriorCleaning = () => {
  return props.customerAttributes.some((attribute) => attribute.attribute === 'restrictInteriorCleaning');
};


/**
 * On before add product addon
 * This is used to check if adding a product has any requirements.
 * At this time, the only requirement (can be) a note.
 * @notation onBeforeAddProductAddon
 * @param addon
 * @param onAfterPreCheck
 */
const onBeforeAddProductAddon = (addon, onAfterPreCheck) => {
  // Check if the addon already is selected
  if (isAddonSelected(props.id, addon.option_id)) { onAfterPreCheck(); return; }
  let note = null
  if (doesAddonHaveNoteRequirement(addon)) {
    note = prompt('Indtast en note til tilvalget');
    if (!note) { Swal.fire(
        'Fejl',
        'Du skal indtaste en note for at tilføje dette tilvalg',
        'error'
    ); return; }
  }
  onAfterPreCheck();
  if (note)
    props.setProductAddonNote(
        props.id,
        addon.option_id,
        note
    );
};

/**
 * On before toggle product addon
 * This is used to check if toggling a product addon has any requirements.
 * At this time, the only requirement (can be) a note.
 * @notation onBeforeToggleProductAddon
 * @param addon
 * @param isAddonCurrentlySelected
 * @param onAfterPreCheck
 */
const onBeforeToggleProductAddon = (addon, isAddonCurrentlySelected, onAfterPreCheck) => {
  // Debug:
  console.log(addon, isAddonCurrentlySelected);
  let note = null
  // If the addon is currently selected, we can remove it without any requirements
  if (isAddonCurrentlySelected) { onAfterPreCheck(); return; }
  // If the addon is not currently selected, we need to check if it has any requirements
  if (doesAddonHaveNoteRequirement(addon)) {
    note = prompt('Indtast en note til tilvalget');
  }
  onAfterPreCheck();
  if (note)
    props.setProductAddonNote(
        props.id,
        addon.option_id,
        note
    );
};

const doesAddonHaveNoteRequirement = (addon) => {
  return addon.product.requires_note;
};

const isAddonRestricted = (addon) => {
  // Check if the addon has "Spot Free" in the name
  if (hasRestrictSpotFree() && addon.name.toLowerCase().includes('spot free')) {
    return true;
  }
  // Check if the addon has "Indvendig vask" in the name
  if (hasRestrictInteriorCleaning() && addon.name.toLowerCase().includes('indvendig vask')) {
    return true;
  }
};
</script>

<template>
  <div>
    <!-- Discount badge (if any) -->
    <div class="is-pulled-right">
      <CustomerProductDiscountDisplay
        v-bind:product="props.product"
        v-bind:customer_discounts="props.customerDiscounts"
        />
    </div>
    <!-- Product box -->
    <div class="pt-2 mb-2 pr-6">
      <div class="columns is-multiline pos-product-box" :class="{ 'is-selected': isSelected }">
        <!-- Product image -->
        <div class="column is-4-desktop is-hidden-touch">
          <img :src="image" alt="Product image" class="image pos-product-image pl-5 mt-4" />
        </div>
        <!-- Product details -->
        <div class="column is-8-desktop">
          <!-- Actual product details -->
          <p class="title is-6">{{ name }}</p>
          <p class="subtitle is-6 mb-0" :style="{ 'color': Colors.global.primaryColor }">
            No. {{ id }}</p>
          <p class="subtitle is-6">{{ description }}</p>
          <!-- White space, to accommodate the design requirements -->
          <p>&nbsp;</p>
          <p class="subtitle is-6 has-text-black">{{ price }} Kr.</p>
        </div>
        <!-- Expandable product details -->
        <div v-if="isSelected" class="column is-12-desktop">
          <!-- Addons -->
          <div class="buttons has-addons is-centered mt-3 mb-0 pl-6" v-if="addons.length > 0">
            <template v-if="hasRestrictAdditionalServices()">
              <button
                  class="button is-small is-fullwidth is-danger"
                  disabled
              >
                <span class="icon is-small">
                  <i class="fas fa-exclamation-triangle"></i>
                </span>
                <span>Ekstra ydelser er ikke tilladt</span>
              </button>
            </template>
            <template v-for="addon in addons" :key="addon.id" v-else>
              <template v-if="!isAddonRestricted(addon)">
                <div
                    class="buttons has-addons is-small is-fullwidth is-flex-wrap-nowrap"
                    :class="{ 'is-link': isAddonSelected(props.id, addon.option_id), 'is-light': !isAddonSelected(props.id, addon.option_id) }"
                >
                  <!-- Addon ( + ) -->
                  <button
                      class="button is-small"
                      @click="onBeforeAddProductAddon(addon, () => addProductAddon(
                        props.id,
                        addon.option_id
                    ))"
                  >
                  <span class="icon is-small">
                    <i class="fas fa-plus"></i>
                  </span>
                  </button>
                  <!-- quantity (if any), Addon name, price -->
                  <button
                      class="button is-small"
                      :class="{ 'is-link': isAddonSelected(props.id, addon.option_id), 'is-light': !isAddonSelected(props.id, addon.option_id) }"
                      @click="onBeforeToggleProductAddon(addon, isAddonSelected(props.id, addon.option_id), () => toggleProductAddon(props.id, addon.option_id))"
                      @mouseenter="showAddonPopper(addon, $event.target)"
                      @mouseleave="hideAddonPopper(addon, $event.target)"
                  >
                    <template v-if="isAddonSelected(props.id, addon.option_id)">
                      {{ getProductAddonQuantity(props.id, addon.option_id) }} x
                    </template>
                    {{ addon.name }} / {{ getAddonPrice(addon.id) }} Kr.
                  </button>
                  <!-- Addon ( - ) -->
                  <button
                      class="button is-small"
                      :disabled="!isAddonSelected(props.id, addon.option_id)"
                      @click="subtractProductAddon(
                        props.id,
                        addon.option_id
                    )"
                  >
                  <span class="icon is-small">
                    <i class="fas fa-minus"></i>
                  </span>
                  </button>
                </div>
              </template>
              <!-- Addon is restricted -->
              <template v-else>
                <div class="buttons has-addons is-small is-fullwidth is-flex-wrap-nowrap">
                  <button
                      class="button is-small is-fullwidth is-danger"
                      disabled
                  >
                    <span class="icon is-small">
                      <i class="fas fa-exclamation-triangle"></i>
                    </span>
                    <span>{{ addon.name }} er ikke tilladt</span>
                  </button>
                </div>
              </template>
            </template>
          </div>
          <!-- White space, to accommodate the design requirements -->
          <p>&nbsp;</p>
          <!-- Add to cart -->
          <div class="buttons is-centered mt-2 mb-3 pl-6">
            <button
                class="button is-link is-small is-fullwidth"
                @click="emitAddToCart(id)"
            >
              <span class="icon is-small">
                <i class="fas fa-cart-plus"></i>
              </span>
              <span>Tilføj til kurv</span>
            </button>
          </div>
        </div>
        <!-- Expander -->
        <div class="column is-12-desktop">
          <p
              class="has-text-centered pl-6"
              @click="toggleIsSelected"
              @mouseover="expandIcon.classList.add('has-text-link')"
              @mouseleave="expandIcon.classList.remove('has-text-link')"
          >
            <span class="icon is-small" style="color: #c7c7c7;">
              <i
                  class="fas fa-angle-down fa-lg"
                  :class="{ 'fa-rotate-180': isSelected }"
                  aria-hidden="true"
                  ref="expandIcon"
              ></i>
            </span>
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>

</style>