<template>
  <div class="cart-menu">
    <div class="row justify-end">
      <q-select
        v-if="!$rootScope.isHQ()"
        class="cart-select col-auto q-ma-xs justify-end"
        v-model="currentCart"
        :options="$rootScope.cartListFiltered"
        option-label="cart_name"
        option-value="cart_rowid"
        standout="bg-primary text-white"
        dense
        dropdown-icon="expand_more"
        @update:model-value="changeCart"
      />
      <q-btn-dropdown
        v-model="showCartPreviewDialog"
        class="cart-dropdown col-auto q-mx-xs q-mt-xs"
        split
        unelevated
        color="grey-4"
        no-caps
        persistent
        text-color="black"
        dropdown-icon="expand_more"
        style="min-height: 38px"
        @click="
          hasViewCartPermission
            ? cartStore.goToCart()
            : showNoCartPermissionMessage()
        "
        @update:model-value="$rootScope.globalGetCartItemListing"
      >
        <template v-slot:label>
          <div class="row items-center no-wrap">
            <div class="col-auto text-center q-pr-sm text-h5">
              {{ cartItemCount }} Items:
            </div>
            <div
              v-if="$rootScope.isHQ()"
              class="col-auto text-center text-h4 text-bold text-green-9"
            >
              {{ subtotal }}
            </div>
            <div
              v-else
              :class="
                'col-auto text-center text-h4 text-bold ' +
                cartTotals?.shipTotalClass
              "
            >
              {{ subtotal }}
            </div>
            <q-icon right name="shopping_cart">
              <q-tooltip style="font-size: 1em">
                Note - When selected, some promotional carts will limit your
                search results
              </q-tooltip>
            </q-icon>
            <div v-if="$rootScope.isHQ()">CART</div>
          </div>
        </template>

        <!-- Cart preview dialog -->
        <div class="cart-preview rounded-borders shadow-8">
          <q-card flat>
            <q-card-section>
              <div class="relative-position">
                <div class="absolute-top-right">
                  <q-icon
                    size="sm"
                    color="grey"
                    name="close"
                    class="cursor-pointer"
                    @click="showCartPreviewDialog = false"
                  ></q-icon>
                </div>
              </div>
              <div class="text-h4">
                Last {{ cartItemsPreview?.length }} Cart Items
                <q-btn
                  v-if="hasViewCartPermission"
                  color="grey-8"
                  class="q-mx-lg"
                  @click="cartStore.goToCart"
                >
                  View Cart
                </q-btn>
              </div>
            </q-card-section>

            <q-separator />

            <q-card-section>
              <div v-if="!cartItemsPreview || cartItemsPreview.length === 0">
                <em>No Cart Items Found.</em>
              </div>
              <div
                v-else
                v-for="(item, index) in cartItemsPreview"
                class="row cart-preview-item"
                :key="index"
              >
                <template v-if="item && !item.isHidden">
                  <!-- Image -->
                  <div
                    class="col-2 q-pr-md"
                    style="height: 100px; width: 100px"
                  >
                    <img
                      class="product-image"
                      :src="item?.thumb_url"
                      @click="zoomImage(item?.thumb_url)"
                    />
                  </div>

                  <!-- Description -->
                  <div class="col-6 q-px-xs">
                    <div class="q-pb-xs">{{ item.part_num }}</div>
                    <div class="item-description">
                      {{ globalStore.decodeHtml(item.description) }}
                    </div>
                    <div class="text-bold q-mt-xs">
                      Qty: {{ item?.qty_ord }}
                    </div>
                  </div>

                  <!-- Price -->
                  <div
                    v-if="item.confirmed === 'checked'"
                    class="col-3 q-pl-xs row justify-center"
                  >
                    <div class="col-auto justify-start">
                      <div>{{ getItemPrice(item) }}</div>
                      <div class="confirmed text-italic q-pt-sm">
                        Cannot delete confirmed items
                      </div>
                    </div>
                  </div>

                  <div v-else class="col-1 row items-start">
                    <div class="col-3 row q-pl-sm">
                      {{ getItemPrice(item) }}
                    </div>
                    <q-icon
                      v-if="item.confirmed === ''"
                      name="o_cancel"
                      color="orange"
                      size="xs"
                      class="cursor-pointer q-pb-sm q-pl-sm"
                      @click="doRemoveItemFromCart(item)"
                    />
                  </div>
                </template>
                <template v-else-if="item && item.isHidden">
                  <em>Item # {{ item?.part_num }} has been deleted.</em>
                </template>
              </div>
            </q-card-section>
          </q-card>
        </div>
      </q-btn-dropdown>
    </div>
    <q-dialog v-model="productImageZoomDialog">
      <q-img
        fit="contain"
        :src="zoomedItemUrl"
        @click="productImageZoomDialog = false"
      />
    </q-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';

const globalStore = window.PiniaStores.useGlobalStore();
const { toCurrency, hasGroupPermission } = globalStore;
const { $rootScope, currentCart, cartItemsPreview, showAccountMenu } =
  window.Pinia.storeToRefs(globalStore);
const cartStore = window.PiniaStores.useCartStore();
const { cartItemCount, cartSubtotal, cartTotals } =
  window.Pinia.storeToRefs(cartStore);

const zoomedItemUrl = ref();
const productImageZoomDialog = ref(false);
const showCartPreviewDialog = ref(false);

const subtotal = computed(() => toCurrency(cartSubtotal.value));

const hasViewCartPermission = computed(() =>
  hasGroupPermission(['-Menu-ViewCart']),
);

const showNoCartPermissionMessage = () => {
  globalStore.$q.dialog({
    message: 'You do not have permission to View Cart.',
  });
};

const getItemPrice = (item) =>
  toCurrency(
    parseFloat(item.price.replace(/,/g, '')) * parseInt(item?.qty_ord),
  );

const zoomImage = (imageUrl) => {
  if (imageUrl) {
    zoomedItemUrl.value = imageUrl?.trim();
    productImageZoomDialog.value = true;
  }
};

const doRemoveItemFromCart = (item) => {
  $rootScope.value.globalDeleteCartItem(item.cartitem_rowid, item);
};

const changeCart = () => {
  $rootScope.value.updActiveCartAndCustNum(currentCart.value);
  // TODO: refresh cart preview while it is opened
  showCartPreviewDialog.value = false;
  // if (showCartPreviewDialog.value) $rootScope.value.globalGetCartItemListing();
};

watch(showAccountMenu, () => {
  if (showAccountMenu.value) {
    showCartPreviewDialog.value = false;
  }
});
</script>

<style scoped>
.cart-select,
.cart-dropdown {
  border: lightgray solid 1px;
  border-radius: 4px;
}
.cart-preview {
  min-width: 400px;
  max-width: 400px;
  max-height: 100vh;
  background-color: white;
}
.cart-menu .row:before {
  display: inherit;
}
.cart-menu label {
  margin-bottom: 0;
}
.confirmed {
  font-size: 0.8em;
  line-height: 1.2;
}
.cart-preview-item {
  padding: 16px 0;
  border-bottom: 1px solid #cccccc;
}
.cart-preview-item:first-child {
  padding-top: 0;
}
.item-description {
  line-height: 1.2;
}
.paidfreight {
  color: #820202 !important;
}
.freefreight {
  color: #006b00 !important;
}
.freefreightaddonfees {
  color: #004283 !important;
}
.product-image {
  max-height: 100px;
  max-width: 100px;
  padding-right: 10px;
}
</style>
