<script setup>
import { ref } from 'vue';
import { customer_id, notes, isCustomerBarred, customer_name, reference, reg_1, reg_2, reg_3, searchAndSelectCustomer, 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";
import LicensePlateReg1Input from "@/components/forms/department/pos/input/LicensePlateReg1Input.vue";
import CustomerSearchFieldPos from "@/components/forms/department/pos/input/customerSearchFieldPos.vue";
import ExpandableContentBox from "@/components/displays/boxes/ExpandableContentBox.vue";
import WhiteBox from "@/components/displays/boxes/WhiteBox.vue";
import OrderContentTable from "@/components/displays/superuser/tables/OrderContentTable.vue";
import OrderItemsTable from "@/components/displays/department/pos/order/orderItemsTable.vue";
import VehicleCustomerSuggestionsPos from "@/components/forms/department/pos/input/vehicleCustomerSuggestionsPos.vue";

const isRegistrationNumbersExpanded = ref(false);
const isOtherExpanded = ref(false);

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();
  }
};

const vehicleObject = ref(null);

const setVehicleObject = (emittedVehicleObject) => {
  // Set the vehicle object to the ref
  vehicleObject.value = emittedVehicleObject;
  // Console log the reference
  if (vehicleObject.value && vehicleObject.value.reference) {
    reference.value = vehicleObject.value.reference;
  } else {
    // Reset the reference, if the vehicle object does not have a reference
    reference.value = '';
  }
};

const bookingObject = ref(null);
const setBookingObject = (emittedBookingObject) => {
  // Set the booking object to the ref
  bookingObject.value = emittedBookingObject;
  // Check if there's a reference in the booking object
  if (emittedBookingObject && emittedBookingObject.reference_number) {
    reference.value = emittedBookingObject.reference_number;
  }
};

const ucFirst = (str) => {
  return str.charAt(0).toUpperCase() + str.slice(1);
};

const isUserCurrentlyInFocusReg1 = ref(false);
const setFocusStateReg1 = (isFocused) => {
  isUserCurrentlyInFocusReg1.value = isFocused;
};


const customerHasAttribute = (attribute) => {
  // Check if the user has the attribute
  if (customer_attributes.value === null) {
    return false;
  }
  if (customer_attributes.value.length === 0) {
    return false;
  }
  // Check if the attribute is in the list
  for (let i = 0; i < customer_attributes.value.length; i++) {
    if (customer_attributes.value[i].attribute === attribute) {
      return true;
    }
  }
};

</script>

<template>
  <div>
    <!-- License plate input fields -->
    <!-- License plate 1 -->
    <div class="field">
      <div class="is-float-right">
        <!-- Colors: icon text -->
        <div class="has-text-left">
        <span>
          <span class="icon has-text-success">
            <i class="fas fa-circle"/>
          </span>
          <span>Verificeret af kunde</span>
        </span>
        <span>
          <span class="icon has-text-warning">
            <i class="fas fa-circle"/>
          </span>
          <span>Kendt</span>
        </span>
        <span>
          <span class="icon has-text-grey">
            <i class="fas fa-circle"/>
          </span>
          <span>Ikke Kendt</span>
        </span>
        <span>
          <span class="icon has-text-danger">
            <i class="fas fa-circle"/>
          </span>
          <span>Brug betalingskort</span>
        </span>
        <span>
          <span class="icon has-text-link">
            <i class="fas fa-circle"/>
          </span>
          <span>Booket (fremt. opdat.)</span>
        </span>
      </div>
      </div>
      <label class="label">{{SessionUser.objects.orders.columns.reg_1.label}}</label>
      <div class="control">
        <LicensePlateReg1Input
        :tabindex="0"
        @update:vehicleObject="setVehicleObject"
        @update:focus="setFocusStateReg1"
        @update:bookingObject="setBookingObject"
        />
      </div>
    </div>
    <!-- License plate 2 -->
    <div class="field">
      <div class="is-pulled-right">
        <div class="tag is-small is-clickable" @click="isRegistrationNumbersExpanded = !isRegistrationNumbersExpanded">
          <span>
            {{ (isRegistrationNumbersExpanded ? (SessionUser.objects.global.language.hide) : (SessionUser.objects.global.language.show)) + ' ' + SessionUser.objects.orders.columns.reg_3.label}}
          </span>
        </div>
      </div>
      <label class="label">{{ SessionUser.objects.orders.columns.reg_2.label }}</label>
      <LicensePlateInput :tab-index="2"
                         @keydown="keyDownNextInput($event, (isRegistrationNumbersExpanded ? 'reg_3' : 'reference'))"
                         input-id="reg_2"
                         v-model:inputModel="reg_2"
                         :customer_number="parseInt(customer_id) || 0"
                         v-bind:actual-value="reg_2"
                         v-bind:reg_1="reg_1"
                         v-bind:customer_id="parseInt(customer_id) || 0"
      />
    </div>
    <!-- License plate 3 -->
    <div class="field" v-show="isRegistrationNumbersExpanded">
      <label class="label">{{ SessionUser.objects.orders.columns.reg_3.label }}</label>
      <LicensePlateInput :tab-index="3"
                         @keydown="keyDownNextInput($event, 'reference')"
                         input-id="reg_3"
                         v-model:inputModel="reg_3"
                         :customer_number="parseInt(customer_id) || 0"
                         v-bind:actual-value="reg_3"
      />
    </div>
    <!-- Reference field -->
    <div class="field" v-if="customerHasAttribute('requiresReferenceNumber')">
      <label class="label">{{SessionUser.objects.orders.columns.reference.label}}</label>
      <div class="control">
        <input
            type="text"
            class="input has-sharp-edges"
            id="reference"
            :tabindex="4"
            v-model="reference"
            @keydown="keyDownNextInput($event, 'customer_id')"
        />
      </div>
    </div>
    <!-- Notes -->
    <PosNotes :notes="notes" :is-loading="false" :isAddFormVisible="false" :isOldNotesVisible="true" class="mb-3"/>
    <!-- If the vehicle is not registered to a customer -->
    <template v-if="(!vehicleObject || !vehicleObject.customer_id) && reg_1.length > 0">
      <div class="divider">{{SessionUser.objects.global.language.select}} {{ SessionUser.objects.global.language.customer }}</div>
      <customerSearchFieldPos />
      <vehicleCustomerSuggestionsPos
        v-bind:reg_1="reg_1"
        @customerSelected="searchAndSelectCustomer"
        />
    </template>
    <!-- Expandable content box for rarely used inputs -->
    <ExpandableContentBox
        v-bind:expanded="isOtherExpanded"
        @update:expanded="isOtherExpanded = $event"
    >
      <template #expandedContent>
        <!-- If the vehicle is registered to a customer -->
        <template v-if="vehicleObject && vehicleObject.customer_id">
          <!-- Divider -->
          <div class="divider">{{ SessionUser.objects.vehicles.meta.labels.single.toUpperCase() }}</div>
          <!-- Vehicle information -->
          <div class="card">
            <div class="card-header">
              <!-- Icon -->
              <div class="card-header-icon">
            <span class="icon is-small">
              <i class="fas fa-car" aria-hidden="true"></i>
            </span>
              </div>
              <!-- Vehicle registration number -->
              <div class="card-header-title">{{ SessionUser.objects.products.functions.getProductName(parseInt(vehicleObject.type)) }}</div>
              <!-- Subscription -->
              <div class="card-header-icon">
            <span
                class="tag is-light"
                :class="{
                  'is-success': vehicleObject.wash_subscription,
                  'is-info': !vehicleObject.wash_subscription
                }"
            >
              {{vehicleObject.wash_subscription
                ? SessionUser.objects.global.language.have
                : SessionUser.objects.global.language.have_not
              }} {{ SessionUser.objects.vehicles.columns.wash_subscription.label.toLowerCase() }}</span>
              </div>
            </div>
            <!-- Vehicle information -->
            <div class="card-content">
              <div class="content">
                <!-- Suggest order items -->
                <div class="columns">
                  <!-- Last time, the vehicle was washed -->
                  <div class="column is-auto-fill" v-if="vehicleObject.last_order_id">
                    <div class="divider">{{ SessionUser.objects.global.language.last_wash }}</div>
                    <!-- Content of the last wash -->
                    <order-content-table v-bind:order-id="vehicleObject.last_order_id" :displayPrice="false" :displayReference="false" :display-notes="false"/>
                    <!-- Copy last wash content -->
                    <div class="control mt-3">
                      <button
                          class="button is-small is-light is-fullwidth" disabled
                      >
                    <span class="icon is-small">
                      <i class="fas fa-copy" aria-hidden="true"></i>
                    </span>
                        <span>{{ SessionUser.objects.global.language.copy }} {{ SessionUser.objects.global.language.last_wash.toLowerCase() }}</span>
                      </button>
                    </div>
                  </div>
                  <!-- Wash subscription -->
                  <div class="column is-6" v-if="vehicleObject.wash_subscription">
                    <div class="divider is-success">{{ SessionUser.objects.vehicles.columns.wash_subscription.label }}</div>
                    <!-- Content of the wash subscription -->
                    <table class="table is-fullwidth">
                      <thead>
                      <tr>
                        <th>{{ucFirst(SessionUser.objects.products.meta.labels.single)}}</th>
                        <th>{{ucFirst(SessionUser.objects.global.language.quantity)}}</th>
                      </tr>
                      </thead>
                      <tbody>
                      <tr>
                        <td>{{ SessionUser.objects.products.functions.getProductName(parseInt(vehicleObject.type)) }}</td>
                        <td>1</td>
                      </tr>
                      <template v-for="item in vehicleObject.addons.list" :key="item.id">
                        <!-- If the item is a primary item, show it -->
                        <tr>
                          <!-- If the item is included in the invoice, show it normally -->
                          <td>+ {{ item.product.name }}</td>
                          <td>{{ item.amount }}</td>
                        </tr>
                      </template>
                      </tbody>
                    </table>

                    <!-- Copy last wash subscription content -->
                    <div class="control mt-3">
                      <button
                          class="button is-small is-light is-fullwidth is-success" disabled
                      >
                    <span class="icon is-small">
                      <i class="fas fa-copy" aria-hidden="true"></i>
                    </span>
                        <span>{{ SessionUser.objects.global.language.copy }} {{ SessionUser.objects.vehicles.columns.wash_subscription.label.toLowerCase() }}</span>
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!-- Vehicle object -->
          <!--<pre>{{vehicleObject}}</pre>-->
        </template>
        <!-- Divider -->
        <div class="divider">{{ SessionUser.objects.global.language.other }}</div>
        <!-- Customer search field (Located discreetly here, if the vehicle is registered to a customer) -->
        <CustomerSearchFieldPos v-if="vehicleObject" />
        <!-- Reference field -->
        <div class="field" v-if="!customerHasAttribute('requiresReferenceNumber')">
          <label class="label">{{SessionUser.objects.orders.columns.reference.label}}</label>
          <div class="control">
            <input
                type="text"
                class="input has-sharp-edges"
                id="reference"
                :tabindex="4"
                v-model="reference"
                @keydown="keyDownNextInput($event, 'customer_id')"
            />
          </div>
        </div>
        <!-- Add notes -->
        <PosNotes :notes="notes" :is-loading="false" :isAddFormVisible="SessionUser.adminUser" :isOldNotesVisible="false" :is-label-visible="true" class="mt-3" v-if="isCustomerSelected()" />
      </template>
    </ExpandableContentBox>
  </div>
</template>

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