<script setup>
import { ref, defineProps, defineEmits } from "vue";
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import InvoiceOrdersPagination
  from "@/components/displays/pagination/models/SuperUserDashboard/InvoiceOrdersPagination.vue";
import ElementTabsBox from "@/components/displays/boxes/ElementTabsBox.vue";
import CollectedOrderInvoicesOverview
  from "@/views/dashboards/superUserDashboard/collectedOrderInvoices/CollectedOrderInvoicesOverview.vue";
import { customer_id, searchAndSelectCustomer, isCustomerSelected } from "@/components/shop/POSDepartmentProcess.vue";
import PosSelectedCustomer from "@/components/displays/department/pos/PosSelectedCustomer.vue";
import CollectedOrderInvoices from "@/views/dashboards/superUserDashboard/CollectedOrderInvoices.vue";
import VehiclesPagination from "@/components/displays/pagination/models/UserDashboard/VehiclesPagination.vue";
import VehiclesTable from "@/components/displays/user/vehicles/vehiclesTable.vue";
import OrdersTable from "@/components/displays/department/pos/orders/ordersTable.vue";
const props = defineProps({
  user_id: {
    type: Number,
    required: false,
    default: null,
  },
  customer_id: {
    type: Number,
    required: false,
    default: null,
  },
});

const tabs = ref([
  { name: SessionUser.objects.global.language.customer, slot: 'customer', icon: 'fas fa-user', hidden: false },
  { name: SessionUser.objects.vehicles.meta.title, slot: 'vehicles', icon: 'fas fa-car', hidden: false },
  { name: SessionUser.objects.vehicles.columns.wash_subscription.label + ' ' + SessionUser.objects.collectedOrderInvoices.meta.labels.multiple, slot: 'subscription', icon: 'fas fa-file-invoice', hidden: false },

])

const emit = defineEmits(["closeModal", "saveChanges"]);

const closeModal = () => {
  emit("closeModal");
}

// Listen for esc key to close the modal
const handleKeydown = (event) => {
  if (event.key === "Escape") {
    closeModal();
  }
};
window.addEventListener("keydown", handleKeydown);

const user = ref(null);

const loadUser = async () => {
  if (props.user_id) {
    // Load the user from the server
    SessionUser.request(
        '/superuser/user',
        'GET',
        {
          user_id: props.user_id,
        },
    ).then(response => {
      user.value = response.data.data;
      // Select the customer if it is not null
      if (user.value.customer_number) {
        customer_id.value = user.value.customer_number;
        searchAndSelectCustomer(user.value.customer_number);
      }
      // Load the vehicles for the user
      getUserVehicles();
    }).catch(error => {
      console.error("Error loading user:", error);
    })
  }
}

const getUserKey = (key, fallback = null, loading = null) => {
  if (user.value === null) {
    return loading ? loading : fallback;
  }
  if (user.value[key] === undefined) {
    return fallback;
  }
  return user.value[key];
}

const getUserVehicles = () => {
  SessionUser.request(
      '/vehicles',
      'GET',
      {
        filters: 'customer_id:' + user.value.customer_number,
      },
  ).then(response => {
    user.value.vehicles = response.data.data;
  }).catch(error => {
    console.error("Error loading vehicles:", error);
  })
}

loadUser();
</script>

<template>
  <div class="modal is-active" ref="modal">
    <div class="modal-background" @click="closeModal"></div>
    <div class="modal-card">
      <header class="modal-card-head">
        <p class="modal-card-title">{{getUserKey('customer_name', 'Unknown customer', 'Loading...')}}</p>
        <button class="delete" aria-label="close" @click="closeModal"></button>
      </header>
      <section class="modal-card-body">
        <!-- Content ... -->
        <template v-if="user !== null">
          <ElementTabsBox
              v-bind:tabs="tabs"
              default-active-tab="customer"
              class="is-boxed"
              :allowCompactWhenOneTab="true"
          >
            <template #customer>
              <PosSelectedCustomer v-if="isCustomerSelected"/>
            </template>
            <template #vehicles>
              <VehiclesTable
                :vehicles="user.vehicles"
                :show_add_vehicle="false"
                :compact="true"
                :reload-list="getUserVehicles"
                />
            </template>
            <template #subscription>
              <OrdersTable :orders="user.wash_subscription_transactions" :compact="true" :reload-list="loadUser" />
            </template>
            <!--
            <template #monthly>
              <OpenCustomerInvoicePagination :auto-load="true" :invoice-per-order="false" />
            </template>
            <template #orderly>
              <OpenCustomerInvoicePagination :auto-load="true" :invoice-per-order="true" />
            </template>
            -->

          </ElementTabsBox>
        </template>
        <!-- Loading state -->
        <template v-else>
          <div class="content">
            <p>Fetching data...</p>
            <p>Please wait while we load the data.</p>
          </div>
          <progress class="progress is-small is-dark" max="100">Loading...</progress>
        </template>
      </section>
      <footer class="modal-card-foot">
        <div class="buttons">
          <button
              class="button is-success"
              @click="loadUser"
          >{{SessionUser.objects.global.language.reload}}</button>
          <button class="button">{{ SessionUser.objects.global.language.close }}</button>
        </div>
      </footer>
    </div>
  </div>
</template>

<style scoped>

</style>