<script setup>
import { ref } from 'vue';
import { customer_id, notes, isCustomerBarred, customer_name, department_id, reference, reg_1, reg_2, reg_3, selectCustomer, isCustomerSelected, customer_attributes } from "@/components/shop/POSDepartmentProcess.vue";
import CustomerSearchField from "@/components/search/economic/customerSearchField.vue";
import { searchCustomerResults } from "@/components/search/economic/customerSearch.vue";
import PosNotes from "@/components/displays/department/pos/PosNotes.vue";
import { isSearching } from "@/components/search/economic/customerSearch.vue";
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import LicensePlateInput from "@/components/forms/department/pos/input/LicensePlateInput.vue";

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]);
    selectedDropdownItem.value = -1;
    // Set the active input to the reference field
    document.getElementById('reference').focus();
  }
};

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>
    <div class="field" :class="{'is-hidden': isCustomerSelected()}">
      <label class="label">Customer Search</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">
          Clear
        </button>
      </p>
    </div>
    <PosNotes :notes="notes" :is-loading="false" :isAddFormVisible="false" :isOldNotesVisible="true" class="mb-3"/>
    <div class="field">
      <label class="label">
        <template v-if="customer_id !== 999">
          Reference nr.
        </template>
        <template v-else>
          <span class="has-text-link">Email adresse til kvittering</span>
        </template>
      </label>
      <div class="control">
        <input
            class="input has-sharp-edges"
            type="text"
            v-model="reference"
            id="reference"
            tabindex="2"
            @keydown="keyDownNextInput($event, 'reg_1')"
            autocomplete="off"
        />
      </div>
      <!-- If the customer has the attribute "requiresReferenceNumber", and the field is empty, show a warning -->
      <p
          class="help has-text-danger"
          v-if="customer_attributes.some((attr) => attr.attribute === 'requiresReferenceNumber') && reference === ''"
      >
        Dette kunde kræver et reference nummer
      </p>
    </div>
    <div class="field">
      <label class="label">Reg 1</label>
      <LicensePlateInput
          :tab-index="3"
          @keydown="keyDownNextInput($event, 'reg_2')"
          input-id="reg_1"
          v-model:inputModel="reg_1"
          v-bind:actual-value="reg_1"
          :customer_number="parseInt(customer_id) || 0"
          class="has-sharp-edges"
      />
      {{   reg_1}}
    </div>
    <div class="field">
      <label class="label">Reg 2</label>
      <LicensePlateInput :tab-index="4" @keydown="keyDownNextInput($event, 'reg_3')" input-id="reg_2" v-model:inputModel="reg_2" :customer_number="parseInt(customer_id) || 0" v-bind:actual-value="reg_2" />
      {{ reg_2}}
    </div>
    <div class="field">
      <label class="label">Reg 3</label>
      <!--<div class="control">
        <input class="input reg-input" type="text" v-model="reg_3" tabindex="5" @keydown="keyDownNextTabIndexButton($event, 6)" id="reg_3" />
      </div> -->
      <LicensePlateInput :tab-index="5" @keydown="keyDownNextTabIndexButton($event, 6)" input-id="reg_3" v-model:inputModel="reg_3" :customer_number="parseInt(customer_id) || 0" v-bind:actual-value="reg_3" />
      {{ reg_3}}
    </div>
  </div>
  <PosNotes :notes="notes" :is-loading="false" :isAddFormVisible="SessionUser.adminUser" :isOldNotesVisible="false" :is-label-visible="true" class="mt-3" v-if="isCustomerSelected()" />
</template>

<style scoped>
.input.has-sharp-edges {
  border-radius: 0;
}
</style>