<script setup>
import { ref, defineProps, watch } from 'vue';
import { SessionUser } from "@/components/session/token/SessionUser.vue";

const props = defineProps({
    // Will use the product prop to get the product (To avoid multiple API calls)
    product: {
        type: Object,
        default: null
    },
    // The Customer discounts
    customer_discounts: {
        type: Array,
        default: []
    },
});

/** Define the variables */
// The best discount percentage for the customer, based on the product, category and global discounts
const highestEligibleDiscount = ref(0);
// If the category discounts are enabled for the product (bool)product.apply_category_discount
const isCategoryDiscountsEnabled = ref((props.product.category_id !== null) && (props.product.apply_category_discount));
// If the global discounts are enabled for the product, this is exactly the same as the `isCategoryDiscountsEnabled` variable, but without the category_id check
const isGlobalDiscountsEnabled = ref(props.product.apply_category_discount);

// The product discount (if any)
const discount_product = ref(null);
// The category discount (if any)
const discount_category = ref(null);
// The global discount (if any)
const discount_global = ref(null);

// Show the discounts dropdown
const showDiscountsDropdown = ref(false);

/** Define the functions */
// Check if the customer has a discount on the product
const hasDiscountOnProduct = () => {
  return discount_product.value > 0;
}

// Check if the customer has a discount on the category
const hasDiscountOnCategory = () => {
  return discount_category.value > 0;
}

// Check if the customer has a global discount
const hasGlobalDiscount = () => {
  return discount_global.value > 0;
}

// Set the product discount
const setProductDiscount = (percentage) => {
  // Check if the percentage is a number
  if (typeof percentage !== 'number') {
    // Warn the user
    console.error("The percentage is not a number recieved:", percentage);
    // If the percentage is not a number, we'll return
    return;
  }
  discount_product.value = percentage;
}
// Set the category discount
const setCategoryDiscount = (percentage) => {
  // Check if the percentage is a number
  if (typeof percentage !== 'number') {
    // Warn the user
    console.error("The percentage is not a number recieved:", percentage);
    // If the percentage is not a number, we'll return
    return;
  }
  discount_category.value = percentage;
}
// Set the global discount
const setGlobalDiscount = (percentage) => {
  // Check if the percentage is a number
  if (typeof percentage !== 'number') {
    // Warn the user
    console.error("The percentage is not a number recieved:", percentage);
    // If the percentage is not a number, we'll return
    return;
  }
  discount_global.value = percentage;
}


// Debugging function
const getDiscountDebug = () => {
    let line = '#####################'
    console.log(line);
    console.log("Product: ", props.product);
    console.log("Product discount: " + (hasDiscountOnProduct() ? discount_product.value : "No discount set"));
    console.log("Category discount: " + (hasDiscountOnCategory() ? discount_category.value : "No discount set"));
    console.log("Global discount: " + (hasGlobalDiscount() ? discount_global.value : "No discount set"));
    console.log("Category discounts enabled: " + isCategoryDiscountsEnabled.value);
    console.log("Global discounts enabled: " + isGlobalDiscountsEnabled.value);
    console.log("Customer discounts: ", props.customer_discounts);
    console.log("Best discount: " + highestEligibleDiscount.value);
    console.log(line);
}

// Parse the customer discounts
const parseCustomerDiscounts = () => {
  const tmp_discount_product = props.customer_discounts.find((discount) => discount.product_or_category_id === props.product.id && !discount.is_category)
  const tmp_discount_category = props.customer_discounts.find((discount) => discount.product_or_category_id === props.product.category && discount.is_category);
  const tmp_discount_global = props.customer_discounts.find((discount) => discount.id === 999999 && discount.is_category);

  //console.log("Product discount: ", tmp_discount_product);
  //console.log("Category discount: ", tmp_discount_category);
  //console.log("Global discount: ", tmp_discount_global);

  // Set the product discount
  if (tmp_discount_product) {
    setProductDiscount(tmp_discount_product.percentage);
  }
  // Set the category discount
  if (tmp_discount_category) {
    setCategoryDiscount(tmp_discount_category.percentage);
  }
  // Set the global discount
  if (tmp_discount_global) {
    setGlobalDiscount(tmp_discount_global.percentage);
  }
}

// Get the best discount for the customer
const getBestDiscount = () => {
    // Set the best discount to 0
    let tmp_best_discount = 0;
    // Check if the product discount is higher than the current best discount
    if (hasDiscountOnProduct() && discount_product.value > tmp_best_discount) {
        // Since the product discount is higher than the current best discount, we'll set the best discount to the product discount
        tmp_best_discount = discount_product.value;
    }
    // Check if the category discount is higher than the current best discount
    if (hasDiscountOnCategory() && discount_category.value > tmp_best_discount) {
        // Check if the category discounts are enabled for the product
        if (isCategoryDiscountsEnabled.value) {
          // Since the category discount is higher than the current best discount, we'll set the best discount to the category discount
          tmp_best_discount = discount_category.value;
        }
    }
    // Check if the global discount is higher than the current best discount
    if (hasGlobalDiscount() && discount_global.value > tmp_best_discount) {
        // Check if the global discounts are enabled for the product
        if (isGlobalDiscountsEnabled.value) {
          // Since the global discount is higher than the current best discount, we'll set the best discount to the global discount
          tmp_best_discount = discount_global.value;
        }
    }
    // Set the highest eligible discount to the best discount
    highestEligibleDiscount.value = tmp_best_discount;
    // Return the best discount
    return tmp_best_discount;
}

/** Call the functions */
// Parse the customer discounts
parseCustomerDiscounts();
// Get the best discount for the customer
getBestDiscount();
// Debug the discount
//getDiscountDebug();

/** Watch the props */
// Watch the product prop, to update the discounts when the discounts change (or initially loads)
watch(() => props.customer_discounts, () => {
    // Parse the customer discounts
    parseCustomerDiscounts();
    // Get the best discount for the customer
    getBestDiscount();
    // Debug the discount
    //getDiscountDebug();
});
</script>

<template>
    <div>
        <!-- The dropdown -->
      <div class="dropdown is-right" :class="{ 'is-active': showDiscountsDropdown }">
        <div class="dropdown-trigger" @mouseover="showDiscountsDropdown = true" @mouseleave="showDiscountsDropdown = false">
          <span
              aria-haspopup="true"
              aria-controls="dropdown-menu"
              v-if="highestEligibleDiscount > 0"
              class="tag is-warning is-light is-text text-can-not-select"
          > -{{ highestEligibleDiscount }}%</span>
        </div>
        <div class="dropdown-menu" id="dropdown-menu" role="menu">
          <div class="dropdown-content py-0">
            <div class="list has-overflow-ellipsis" style="width: 340px">
              <!-- Best discount -->
              <a class="list-item">
                <div class="list-item-content">
                  <div class="list-item-title">Aktiv rabat</div>
                </div>
                <div class="list-item-controls list-item-controls-force-visible">
                  <div class="tags has-addons">
                    <span class="tag is-success is-light"> -{{ highestEligibleDiscount }}%</span>
                  </div>
                </div>
              </a>
              <!-- Product discount -->
              <a class="list-item">
                <div class="list-item-content">
                  <div class="list-item-title">Produkt rabat</div>
                </div>
                <div class="list-item-controls list-item-controls-force-visible">
                  <div class="tags has-addons">
                    <span class="tag is-warning is-light"> -{{ discount_product }}%</span>
                    <span class="tag is-light is-success" v-if="isCategoryDiscountsEnabled">Tilladt</span>
                    <span class="tag is-light is-danger" v-else>Ikke tilladt</span>
                  </div>
                </div>
              </a>
              <!-- Category discount -->
              <a class="list-item">
                <div class="list-item-content">
                  <div class="list-item-title">Kategori rabat</div>
                </div>
                <div class="list-item-controls list-item-controls-force-visible">
                  <div class="tags has-addons">
                    <span class="tag is-warning is-light"> -{{ discount_category }}%</span>
                    <span class="tag is-light is-success" v-if="isCategoryDiscountsEnabled">Tilladt</span>
                    <span class="tag is-light is-danger" v-else>Ikke tilladt</span>
                  </div>
                </div>
              </a>
              <!-- Global discount -->
              <a class="list-item">
                <div class="list-item-content">
                  <div class="list-item-title">E-conomic rabat</div>
                </div>
                <div class="list-item-controls list-item-controls-force-visible">
                  <div class="tags has-addons">
                    <span class="tag is-warning is-light"> -{{ discount_global }}%</span>
                    <span class="tag is-light is-success" v-if="isGlobalDiscountsEnabled">Tilladt</span>
                    <span class="tag is-light is-danger" v-else>Ikke tilladt</span>
                  </div>
                </div>
              </a>
            </div>
          </div>
        </div>
      </div>
  </div>
</template>

<style scoped>
.list-item-controls-force-visible {
  opacity: initial!important;
  visibility: initial!important;
}
.text-can-not-select {
  user-select: none;
}
</style>