<script setup>
import { ref, defineEmits, defineProps } from 'vue';
import { customer_id, isCustomerBarred, customer_name, selectCustomer, isCustomerSelected } from "@/components/shop/POSDepartmentProcess.vue";
import CustomerSearchField from "@/components/search/economic/customerSearchField.vue";
import { searchCustomerResults } from "@/components/search/economic/customerSearch.vue";
import { isSearching } from "@/components/search/economic/customerSearch.vue";
import { SessionUser } from "@/components/session/token/SessionUser.vue";
const props = defineProps({
  onCustomerSelected: {
    type: Function,
    default: () => {}
  }
});
const emit = defineEmits(['update:customer_id', 'onCustomerSelected']);
const selectedDropdownItem = ref(-1);
const showSelector = ref(false);

const arrowKeyHandler = (event) => {
  if (event.key === 'ArrowDown') {
    event.preventDefault();
    if (selectedDropdownItem.value < searchCustomerResults.value.length - 1) {
      selectedDropdownItem.value++;
    }
  }
  if (event.key === 'ArrowUp') {
    event.preventDefault();
    if (selectedDropdownItem.value > -1) {
      selectedDropdownItem.value--;
    }
  }
  if (event.key === 'Enter') {
    event.preventDefault();
    selectCustomer(searchCustomerResults.value[selectedDropdownItem.value]);
    // Emit the customerSelected event
    console.log('Emitting customerSelected event with:', searchCustomerResults.value[selectedDropdownItem.value]);
    emitChange(searchCustomerResults.value[selectedDropdownItem.value]);
    selectedDropdownItem.value = -1;
    // Set the active input to the reference field (if it exists)
    if (document.getElementById('reference')) {
      document.getElementById('reference').focus();
    }
  }
};

const emitChange = (customer) => {
  console.log('Emitting update:customer_id with:', customer);
  emit('update:customer_id', customer.customerNumber);
  emit('onCustomerSelected', customer);
  props.onCustomerSelected(customer);
};

const getSearchIndexByCustomerNumber = (customerNumber) => {
  return searchCustomerResults.value.findIndex((result) => result.customerNumber === customerNumber);
};

// This delay is needed to prevent the dropdown from closing when clicking on a dropdown item (Making the dropdown item clickable)
const lostfocus = () => {
  setTimeout(() => {
    showSelector.value = false;
  }, 200);
};

const keyDownNextInput = (event, field_id) => {
  if (event.key === 'Enter') {
    event.preventDefault();
    document.getElementById(field_id).focus();
  }
};

const keyDownNextTabIndexButton = (event, tabIndex) => {
  if (event.key === 'Enter') {
    event.preventDefault();
    // First unfocus the input field. This is to ensure the sync between the input field and the POSDepartmentProcess.vue data.
    event.target.blur();
    document.querySelector(`button[tabindex="${tabIndex}"]`).click();
  }
};
</script>

<template>
  <div class="field" :class="{'is-hidden': isCustomerSelected()}">
    <label class="label">{{SessionUser.objects.global.language.customer}}</label>
    <div class="control" :class="{'is-loading': isSearching}">
      <CustomerSearchField
          :v-model="customer_id"
          class="input has-sharp-edges"
          type="text"
          :disabled="isCustomerSelected()"
          @keydown="arrowKeyHandler"
          @focusout="selectedDropdownItem = -1; lostfocus()"
          @focusin="showSelector = true"
          :tabindex="isCustomerSelected() ? -1 : 0"
          autocomplete="off"
          id="pos_select_customer_input"
      />
    </div>
    <div class="dropdown" :class="{'is-active': showSelector && searchCustomerResults.length > 0}">
      <div class="dropdown-menu">
        <div class="dropdown-content">
          <a class="dropdown-item customer-drop-down-select" v-for="result in searchCustomerResults" :key="result.id" @click="selectCustomer(result)" :class="{'is-active': getSearchIndexByCustomerNumber(result.customerNumber) === selectedDropdownItem, 'is-drop-down-selected': getSearchIndexByCustomerNumber(result.customerNumber) === selectedDropdownItem, 'has-text-warning': isCustomerBarred(result)}">
            {{ result.name }} - {{ result.customerNumber }} {{ (isCustomerBarred(result) ? ' (Spærret)' : '') }}
          </a>
        </div>
      </div>
    </div>
    <!-- Stripe payment button -->
    <button class="button is-text mt-1" @click="selectCustomer({name: 'Stripe Payment', customerNumber: 999})" :tabindex="isCustomerSelected() ? 1 : -1" :class="{'is-hidden': isCustomerSelected()}" style="text-decoration-line: none;">
      Vælg direkte betaling med betalingskort
    </button>
  </div>
  <div class="field has-addons-right has-addons mt-1" :class="{'is-hidden': !isCustomerSelected()}">
    <p class="control is-expanded">
      <input class="input has-sharp-edges" type="text" v-model="customer_name" disabled />
    </p>
    <p class="control">
      <button class="button is-danger" @click="selectCustomer(null)" :tabindex="isCustomerSelected() ? 1 : -1">
        {{SessionUser.objects.global.language.clear}}
      </button>
    </p>
  </div>
</template>

<style scoped>

</style>