<script setup>
import {ref, defineProps, defineEmits, watch} from 'vue';
import { selectCustomer, isCustomerSelected, customer_id } from "@/components/shop/POSDepartmentProcess.vue";
import { SessionUser } from "@/components/session/token/SessionUser.vue";

const props = defineProps({
  reg_1: {
    type: String,
    required: true,
  },
})

const emit = defineEmits(['customerSelected']);

const getCustomerSuggestionObject = (id, customer_number, customer_name, barred = false) => {
  return {
    id: parseInt(id),
    customer_number: parseInt(customer_number),
    customer_name,
    barred,
  };
}
const customer_suggestions = ref([
    /* Dummy data for testing purposes
  getCustomerSuggestionObject(1, '1234567890', 'John Doe'),
  getCustomerSuggestionObject(2, '0987654321', 'Jane Smith'),
  getCustomerSuggestionObject(3, '1122334455', 'Alice Johnson'),
  getCustomerSuggestionObject(4, '5566778899', 'Bob Brown'),
  getCustomerSuggestionObject(5, '2233445566', 'Charlie Davis'),
  getCustomerSuggestionObject(6, '6677889900', 'Diana Prince'),
  getCustomerSuggestionObject(7, '3344556677', 'Ethan Hunt'),
  getCustomerSuggestionObject(8, '7788990011', 'Felicity Smoak'),
  getCustomerSuggestionObject(9, '4455667788', 'George Clooney'),
  getCustomerSuggestionObject(10, '8899001122', 'Hannah Montana'),
  getCustomerSuggestionObject(11, '5566778899', 'Ian Malcolm'),
  getCustomerSuggestionObject(12, '9988776655', 'Jack Sparrow'),
  getCustomerSuggestionObject(13, '2233445566', 'Katherine Johnson'),
  getCustomerSuggestionObject(14, '6677889900', 'Leonardo DiCaprio'),
  getCustomerSuggestionObject(15, '3344556677', 'Mia Thermopolis'),
     */
]);

const getCustomerSuggestions = () => {
  // Check if the reg_1 prop is provided (and valid)
  if (!props.reg_1) {
    return;
  }
  SessionUser.request(
      '/department/vehicle/customer-suggestions',
      'GET',
      {
        reg_1: props.reg_1,
      },
  ).then(response => {
    // Assuming the response contains an array of customer suggestions
    console.log('Customer suggestions:', response.data.data);
    let suggestions = [];
    for (let i = 0; i < response.data.data.length; i++) {
      suggestions.push(getCustomerSuggestionObject(
          response.data.data[i].id,
          response.data.data[i].customer_number,
          response.data.data[i].customer_name,
          response.data.data[i].barred ?? false,
      ));
    }
    customer_suggestions.value = suggestions;
  }).catch(error => {
    console.error('Error fetching customer suggestions:', error);
  });
}
const isSettingCustomer = ref(false);
const isSettingCustomerToInteger = ref(0);
const isSettingCustomerStartTime = ref(null);
const isSettingCustomerTo = (customer_number) => {
  return isSettingCustomerToInteger.value === parseInt(customer_number);
}

const onClick = (customer) => {
  isSettingCustomer.value = true;
  isSettingCustomerToInteger.value = parseInt(customer.customer_number);
  isSettingCustomerStartTime.value = new Date();
  emit('customerSelected', parseInt(customer.customer_number));
}

watch(() => props.reg_1, (newValue) => {
  resetIsSettingCustomer();
  if (newValue) {
    getCustomerSuggestions();
  } else {
    customer_suggestions.value = [];
  }
});

watch(() => customer_id.value, (newValue) => {
  resetIsSettingCustomer();
});

const resetIsSettingCustomer = () => {
  isSettingCustomer.value = false;
  isSettingCustomerToInteger.value = 0;
  isSettingCustomerStartTime.value = null;
}


// Watch for the isSettingCustomer to reset after 5 seconds
watch(() => isSettingCustomer.value, (newValue) => {
  if (newValue) {
    setTimeout(() => {
      isSettingCustomer.value = false;
      isSettingCustomerToInteger.value = 0;
      isSettingCustomerStartTime.value = null;
    }, 5000);
  }
});

// If the reg_1 is set when the component is mounted, fetch the customer suggestions
if (props.reg_1) {
  getCustomerSuggestions();
}
</script>

<template>
  <div class="field" :class="{'is-hidden': isCustomerSelected()}">
    <div class="control">
      <template v-if="customer_suggestions.length > 0">
        <div class="columns is-multiline is-mobile">
          <!-- Divider -->
          <div class="column is-12 pb-0">
            <div class="divider">{{SessionUser.objects.global.language.previous}} {{SessionUser.objects.global.language.customers}}</div>
          </div>
          <!-- Loop through the customer suggestions and display them -->
          <template v-for="(customer, index) in customer_suggestions" :key="index">
            <div class="column is-6">
              <div class="card">
                <!-- Name of the customer -->
                <div class="card-content">
                  <div class="content">
                    <p class="title is-5">{{ customer.customer_name }}</p>
                    <p class="subtitle is-6">{{ customer.customer_id }}</p>
                  </div>
                  <div class="buttons">
                    <button class="button is-light is-fullwidth" @click="onClick(customer)" :class="{'is-loading': isSettingCustomerTo(customer.customer_number), 'is-danger': customer.barred}" :disabled="isSettingCustomer || customer.barred">
                      <template v-if="customer.barred">
                        <span class="icon">
                          <i class="fas fa-ban"></i>
                        </span>
                        <span>
                          {{SessionUser.objects.global.language.barred}}
                        </span>
                      </template>
                      <template v-else>
                        {{SessionUser.objects.global.language.select}}
                      </template>
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </div>
      </template>
    </div>
  </div>
</template>

<style scoped>

</style>