<script setup>
import LoadButtonWhileAwait from "@/components/request/LoadButtonWhileAwait.vue";
import { showEditOrderItemForm } from "@/components/forms/superUser/editOrderItemForm.vue";
import { removeOrderItem } from "@/components/shop/OrdersItems.vue";
import {ref, watch, defineProps, defineSlots, useSlots, renderSlot } from 'vue';
const props = defineProps(['orderItems', 'orderId', 'loadOrderItems', 'editPossible', 'isLarge']);

import { createPopper } from '@popperjs/core';
import { showPopper, popper, showPopperWithContent, removePopperIfOpen, popperBox} from "@/components/displays/PopperDefault.vue";
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import ActionSettingsWheelButton from "@/components/displays/buttons/ActionSettingsWheelButton.vue";
import ActionSettingsWheelItem from "@/components/displays/buttons/ActionSettingsWheelItem.vue";
import { customer_name, getOrderDetails, setOrderId, order_id, reference, order_notes, reg_1, reg_3, reg_2 } from "@/components/shop/POSDepartmentProcess.vue";
import SpanSkeleton from "@/components/displays/skeletons/SpanSkeleton.vue";
import PosOrderLicensePlates from "@/components/displays/department/pos/order/PosOrderLicensePlates.vue";
import POSOrderReference from "@/components/displays/department/pos/order/POSOrderReference.vue";
import PosNotes from "@/components/displays/department/pos/PosNotes.vue";
import POSOrderNote from "@/components/displays/department/pos/order/POSOrderNote.vue";
// Tabs

const panel_tabs = ref([
  {
    icon: 'fas fa-shopping-cart',
    name: 'Kurv',
    active: true,
  }
]);
// Check if the size is large
const isLarge = props.isLarge !== undefined ? props.isLarge : false;

// Check if the other slot is present
const hasOtherSlot = useSlots().other !== undefined;

// If so, add the other tab
if (hasOtherSlot) {
  panel_tabs.value.push({
    name: 'Indstillinger',
    active: false,
    icon: 'fas fa-cog',
  });
}

const hasDetailsSlot = useSlots().details !== undefined;

// If so, add the other tab
if (hasDetailsSlot) {
  panel_tabs.value.push({
    name: 'Detaljer',
    active: false,
    icon: 'fas fa-info',
  });
}

// Hide the order item while removing
const hideOrderItemWhileRemoving = (id) => {
  document.getElementById('order-item-' + id).style.display = 'none';
};

const getItemRelatedItems = (orderItems, orderItemId) => {
  // Return all items with the item.related_item_id equal to the orderItemId
  return orderItems.filter((orderItem) => orderItem.related_item_id === orderItemId);
};

const isLastRelatedItem = (orderItems, orderItem) => {
  // Get all related items
  const relatedItems = getItemRelatedItems(orderItems, orderItem.related_item_id);
  // If there are no related items, return true
  if (relatedItems.length === 0) {
    return true;
  }
  // If the last related item is the current item, return true
  return relatedItems[relatedItems.length - 1].id === orderItem.id;
};

const registration_numbers = ref({
  1: null,
  2: null,
  3: null,
});


const loadOrder = () => {
  // Wait 100ms before loading the order.
  // This is to ensure that the order_id is set before loading the order.
  setTimeout(() => {
    setOrderId(props.orderId);
    getOrderDetails().then((orderDetails) => {
      const reg_numbers = registration_numbers.value;
      reg_numbers[1] = orderDetails.reg_1;
      reg_numbers[2] = orderDetails.reg_2;
      reg_numbers[3] = orderDetails.reg_3;
    });
  }, 100);
};

const isTabZeroExpanded = ref(false);
const toggleIsSelected = () => {
  isTabZeroExpanded.value = !isTabZeroExpanded.value;
};
const expandIcon = ref(null);

loadOrder();
</script>

<template>
  <div>
    <article class="">
      <!-- Customer name -->
      <SpanSkeleton
          class="title is-5"
        :isSkeleton="!customer_name"
        width="100%"
        height="1.5rem"
        skeleton-class="is-size-4"
        >
        {{ customer_name }}
      </SpanSkeleton>
      <p class="is-7 subtitle mb-2">Transaktion #{{ orderId }}</p><slot name="headingcenter"></slot><span class="is-float-right"><slot></slot></span>
      <p class="panel-tabs" v-if="panel_tabs.length > 1">
        <a v-for="(tab, index) in panel_tabs" :key="index" :class="{'is-active': tab.active}" @click="panel_tabs.forEach(tab => tab.active = false); tab.active = true" >
          <!-- If the tab has an icon, show it -->
          <span v-if="tab.icon" class="icon is-small">
            <i :class="tab.icon"></i>
          </span>
          {{ tab.name }}
        </a>
      </p>
      <!-- Cart -->
      <div v-if="panel_tabs[0].active">
        <div class="panel-block">
          <table class="table is-fullwidth">
            <thead>
              <tr>
                <th>Produkt</th>
                <th style="width: 20%; text-align: right;">Pris (DKK)</th>
                <th v-if="editPossible" style="width: 15%;"></th>
              </tr>
            </thead>
            <tbody>
            <!-- Slot -->
            <slot name="beforeItems"></slot>
            <template v-for="orderItem in orderItems" :key="orderItem.id">
              <tr
                  :id="'order-item-' + orderItem.id"
                  v-if="!orderItem.related_item_id"
                  :style="{ 'border-bottom-style': getItemRelatedItems(orderItems, orderItem.id).length > 0 ? 'hidden' : '' }"
                  style="border-top: 1px solid #f5f5f5;"
              >
                <td>
                  <span>{{ orderItem.product.name }}</span>
                  <!-- Notes (If there are any) -->
                  <span v-if="orderItem.notes"
                        @mouseover="showPopper(
                              popperBox(
                              'Note',
                              orderItem.notes
                              ),
                              $event.target
                            )"
                        @mouseleave="removePopperIfOpen()"
                        @click="showEditOrderItemForm(orderItem.id, orderItem.product.name, orderItem.price, orderItem.notes, orderItem.reference, orderItem.quantity, editPossible).then(() => loadOrderItems())"
                        class="ml-2 is-size-7 has-text-grey is-clickable">
                    <i class="fas fa-comment"></i>
                    Se note
                  </span>
                  <!-- Reference (If there are any) -->
                  <span v-if="orderItem.reference"
                        @mouseover="showPopper(
                            popperBox(
                                'Reference',
                                orderItem.reference
                                ),
                                $event.target
                            )"
                        @mouseleave="removePopperIfOpen()"
                        @click="showEditOrderItemForm(orderItem.id, orderItem.product.name, orderItem.price, orderItem.notes, orderItem.reference, orderItem.quantity, editPossible).then(() => loadOrderItems())"
                        class="ml-2 is-size-7 has-text-grey is-clickable">
                    <i class="fas fa-link"></i>
                    Se reference
                  </span>
                  <!-- Quantity (If it is more than 1) -->
                  <span v-if="orderItem.quantity > 1"
                        @mouseover="showPopper(
                            popperBox(
                                'Antal',
                                orderItem.quantity
                                ),
                                $event.target
                            )"
                        @mouseleave="removePopperIfOpen()"
                        @click="showEditOrderItemForm(orderItem.id, orderItem.product.name, orderItem.price, orderItem.notes, orderItem.reference, orderItem.quantity, editPossible).then(() => loadOrderItems())"
                        class="ml-2 is-size-7 has-text-grey is-clickable">
                    <i class="fas fa-box"></i>
                    Antal: {{ orderItem.quantity }}
                  </span>
                </td>
                <!-- If the price has been changed, show the new price (With a strike-through) and the old price -->
                <td style="width: 20%; text-align: right;" v-if="orderItem.price !== orderItem.product.price">
                  <span
                      @mouseover="showPopper(
                        popperBox(
                            'Pris',
                            'Pris ændret fra ' + orderItem.product.price + ' DKK til ' + orderItem.price + ' DKK / Enhed (' + orderItem.price * orderItem.quantity + ' DKK i alt)'
                            ),
                            $event.target
                        )"
                      @mouseleave="removePopperIfOpen()">
                  <span style="text-decoration: line-through;" class="has-text-dark">{{ orderItem.product.price * orderItem.quantity}}</span> <span>{{ orderItem.price * orderItem.quantity }}</span>
                  </span>
                </td>
                <td style="width: 20%; text-align: right;" v-else>
                  <span
                      @mouseover="showPopper(
                        popperBox(
                            'Pris',
                            orderItem.price + ' DKK / Enhed (' + orderItem.price * orderItem.quantity + ' DKK i alt)'
                            ),
                            $event.target
                        )"
                      @mouseleave="removePopperIfOpen()">
                    {{ orderItem.price * orderItem.quantity }}
                  </span>
                </td>
                <td v-if="editPossible" style="width: 15%;">
                  <div class="buttons is-narrow">
                    <ActionSettingsWheelButton>
                      <template #actions>
                        <ActionSettingsWheelItem
                          label="Slet"
                          icon="fas fa-trash"
                          template="danger"
                          @click="hideOrderItemWhileRemoving(orderItem.id);removeOrderItem(orderItem.id).then(() => loadOrderItems())"
                        />
                        <ActionSettingsWheelItem
                          label="Rediger"
                          icon="fas fa-edit"
                          template="warning"
                          :disabled="!SessionUser.hasPermission('edit_order_items')"
                          @click="showEditOrderItemForm(orderItem.id, orderItem.product.name, orderItem.price, orderItem.notes, orderItem.reference, orderItem.quantity, editPossible, () => loadOrderItems())"
                        />
                      </template>
                    </ActionSettingsWheelButton>
                  </div>
                </td>
              </tr>
              <!-- Related items -->
              <template v-for="relatedItem in getItemRelatedItems(orderItems, orderItem.id)" :key="relatedItem.id">
                <tr
                    :id="'order-item-' + relatedItem.id"
                    :style="{ 'border-bottom-style': isLastRelatedItem(orderItems, relatedItem) ? '' : 'hidden' }"
                >
                  <td>
                    <span class="related-item-text is-one-line-hide-overflow">
                      <span>+ <template v-if="relatedItem.quantity > 1">{{ relatedItem.quantity }} x</template>{{ relatedItem.product.name }}</span>
                    </span>
                    <span class="is-size-7 has-text-grey">
                    <!-- Notes (If there are any) -->
                    <span v-if="relatedItem.notes"
                          @mouseover="showPopper(
                              popperBox(
                              'Note',
                              relatedItem.notes
                              ),
                              $event.target
                          )"
                          @mouseleave="removePopperIfOpen()"
                          @click="showEditOrderItemForm(relatedItem.id, relatedItem.product.name, relatedItem.price, relatedItem.notes, relatedItem.reference, relatedItem.quantity, editPossible).then(() => loadOrderItems())"
                          class="ml-2 is-size-7 has-text-grey is-clickable">
                      <i class="fas fa-comment"></i>
                      Se note
                    </span>
                    <!-- Reference (If there are any) -->
                    <span v-if="relatedItem.reference"
                          @mouseover="showPopper(
                              popperBox(
                                  'Reference',
                                  relatedItem.reference
                                  ),
                                  $event.target
                              )"
                          @mouseleave="removePopperIfOpen()"
                          @click="showEditOrderItemForm(relatedItem.id, relatedItem.product.name, relatedItem.price, relatedItem.notes, relatedItem.reference, relatedItem.quantity, editPossible).then(() => loadOrderItems())"
                          class="ml-2 is-size-7 has-text-grey is-clickable">
                      <i class="fas fa-link"></i>
                      Se reference
                    </span>
                    </span>
                  </td>
                  <!-- If the price has been changed, show the new price (With a strike-through) and the old price -->
                  <td style="width: 20%; text-align: right;" v-if="relatedItem.price !== relatedItem.product.price">
                    <span
                        @mouseover="showPopper(
                            popperBox(
                                'Pris',
                                'Pris ændret fra ' + relatedItem.product.price + ' DKK til ' + relatedItem.price + ' DKK / Enhed (' + relatedItem.price * relatedItem.quantity + ' DKK i alt)'
                                ),
                                $event.target
                            )"
                        @mouseleave="removePopperIfOpen()">
                    <span style="text-decoration: line-through;" class="has-text-dark related-item-text">{{ relatedItem.product.price * relatedItem.quantity}}</span> <span>{{ relatedItem.price * relatedItem.quantity }} DKK</span>
                    </span>
                  </td>
                  <td style="width: 20%; text-align: right;" v-else>
                    <span
                        class="related-item-text"
                        @mouseover="showPopper(
                            popperBox(
                                'Pris',
                                relatedItem.price + ' DKK / Enhed (' + relatedItem.price * relatedItem.quantity + ' DKK i alt)'
                                ),
                                $event.target
                            )"
                        @mouseleave="removePopperIfOpen()">
                      {{ relatedItem.price * relatedItem.quantity }}
                    </span>
                  </td>
                  <td v-if="editPossible" style="width: 15%;">
                    <div class="buttons is-narrow">
                      <ActionSettingsWheelButton>
                        <template #actions>
                          <ActionSettingsWheelItem
                            label="Slet"
                            icon="fas fa-trash"
                            template="danger"
                            @click="hideOrderItemWhileRemoving(relatedItem.id);removeOrderItem(relatedItem.id).then(() => loadOrderItems())"
                          />
                          <ActionSettingsWheelItem
                            label="Rediger"
                            icon="fas fa-edit"
                            template="warning"
                            :disabled="!SessionUser.hasPermission('edit_order_items')"
                            @click="showEditOrderItemForm(relatedItem.id, relatedItem.product.name, relatedItem.price, relatedItem.notes, relatedItem.reference, relatedItem.quantity, editPossible, () => loadOrderItems())"
                          />
                        </template>
                      </ActionSettingsWheelButton>
                    </div>
                  </td>
                </tr>
                </template>
            </template>
              <slot name="bottom-order-items"></slot>
            </tbody>
            <tfoot>
              <tr>
                <td>Total</td>
                <td colspan="1" style="width: 20%; text-align: right;">
                  <span
                      @mouseover="showPopper(
                        popperBox(
                            'Total',
                            'Total pris for ordren: ' + orderItems.reduce((acc, orderItem) => acc + orderItem.price * orderItem.quantity, 0) + ' DKK'
                            ),
                            $event.target
                        )"
                      @mouseleave="removePopperIfOpen()">
                    {{ orderItems.reduce((acc, orderItem) => acc + orderItem.price * orderItem.quantity, 0) }} DKK
                  </span>
                </td>
                <td v-if="editPossible" style="width: 15%;"></td>
              </tr>
            </tfoot>
          </table>
        </div>
        <div class="panel-block" v-if="$slots.bottom">
          <!-- Bottom slot -->
          <slot name="bottom"></slot>
        </div>
      </div>
      <!-- Advanced -->
      <div v-if="panel_tabs[1] && panel_tabs[1].active">
        <div class="panel-block is-fullwidth">
          <!-- Other slot -->
          <slot name="other"></slot>
        </div>
      </div>
      <!-- Details -->
      <div v-if="panel_tabs[2] && panel_tabs[2].active">
        <div class="panel-block is-fullwidth">
          <!-- Details slot -->
          <slot name="details"></slot>
        </div>
      </div>
      <div v-if="panel_tabs[0].active">
        <div class="columns is-multiline" :class="{ 'is-flex-direction-row-reverse': isLarge}" v-if="isTabZeroExpanded">
          <div class="column" :class="isLarge ? 'is-6' : 'is-12'">
            <!-- License plates -->
            <div v-if="isLarge" class="divider is-size-7">Nummerplader</div>
            <PosOrderLicensePlates
                v-bind:registration_numbers="registration_numbers"
                v-bind:loadOrder="loadOrder"
                v-bind:order_id="order_id"
            />
          </div>
          <div class="column" :class="isLarge ? 'is-6' : 'is-12'">
            <!-- Reference -->
            <div v-if="isLarge" class="divider is-size-7">Reference</div>
            <POSOrderReference
                v-bind:order_id="order_id"
                v-bind:loadOrder="loadOrder"
                v-bind:reference="reference"
            />
          </div>
          <div class="column is-12">
            <!-- Notes -->
            <div class="divider is-size-7">Ordre note</div>
            <POSOrderNote
                v-bind:order_id="order_id"
                v-bind:loadOrder="loadOrder"
                v-bind:note="order_notes"
            />
          </div>
        </div>
        <!-- Expander -->
        <div class="column is-12-desktop">
          <p
              class="has-text-centered"
              @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': isTabZeroExpanded }"
                aria-hidden="true"
                ref="expandIcon"
            ></i>
          </span>
          </p>
        </div>
      </div>
    </article>
  </div>
</template>

<style scoped>
.related-item-text {
  color: #4a4a4a;
  font-size: 0.9rem;
  height: 10px;

  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: clip;
  :hover {
    overflow: visible;
  }
}

</style>