<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";
import InvoicesTable from "@/components/displays/user/invoices/invoicesTable.vue";
import CollectedOrderInvoicesTable from "@/components/displays/superuser/tables/collectedOrderInvoicesTable.vue";
import CollectedOrderInvoicesPagination
  from "@/components/displays/pagination/models/SuperUserDashboard/CollectedOrderInvoicesPagination.vue";
const props = defineProps({
  customer_id: {
    type: Number,
    default: null,
    required: true,
  },
  onInvoiceCollectionSelected: {
    type: Function,
    default: () => {}
  },
  onClose: {
    type: Function,
    default: () => {}
  },
});


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

const closeModal = () => {
  emit("closeModal");
  props.onClose();
}

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

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

const selectInvoiceCollection = (invoiceCollection) => {
  props.onInvoiceCollectionSelected(invoiceCollection);
  emit("saveChanges", invoiceCollection);
};

const get_invoice_collection_object = (invoiceCollection) => {
  return {
    id: invoiceCollection.id, // The invoice collection ID
    customer_number: props.customer_id ?? null, // The customer number associated with the invoice collection
    customer_name: invoiceCollection.customer_name ?? null, // The name of the customer associated with the invoice collection
    created_at: invoiceCollection.created_at ?? null, // The date the invoice collection was created
    updated_at: invoiceCollection.updated_at ?? null, // The date the invoice collection was last updated
    closed_at: invoiceCollection.closed_at ?? null, // The date the invoice collection was closed (if applicable)
    processor: invoiceCollection.processor ?? null, // The processor associated with the invoice collection (if applicable)
    external_id: invoiceCollection.external_id ?? null, // The external ID associated with the invoice collection (if applicable)
    orders: [], // The orders associated with the invoice collection
  }
}
const invoice_collections = ref([
    get_invoice_collection_object({
      id: 1,
      customer_number: props.customer_id,
      created_at: "2023-10-01",
      updated_at: "2023-10-02",
      closed_at: null,
      processor: 1,
      external_id: "EXT-001",
    }),
    get_invoice_collection_object({
      id: 2,
      customer_number: props.customer_id,
      created_at: "2023-10-03",
      updated_at: "2023-10-04",
      closed_at: null,
      processor: 2,
      external_id: "EXT-002",
    }),
    get_invoice_collection_object({
      id: 3,
      customer_number: props.customer_id,
      created_at: "2023-10-05",
      updated_at: "2023-10-06",
      closed_at: null,
      processor: 3,
      external_id: "EXT-003",
    }),
    get_invoice_collection_object({
      id: 4,
      customer_number: props.customer_id,
      created_at: "2023-10-07",
      updated_at: "2023-10-08",
      closed_at: null,
      processor: 4,
      external_id: "EXT-004",
    }),
]);

const selectedDate = ref('');

const onClickCreateNewInvoiceCollection = async () => {
  // Logic to create a new invoice collection
  console.log("Creating new invoice collection... Selected date:", selectedDate.value);
  await SessionUser.objects.collectedOrderInvoices.add(
      props.customer_id,
      'Manual invoice collection',
      'Created by user',
      selectedDate.value
  ).then((response) => {
    console.log(response.data.data.id, "Invoice collection created successfully");
    // Select the newly created invoice collection
    selectInvoiceCollection(parseInt(response.data.data.id));
  }).catch((error) => {
    console.error(error, "Error creating invoice collection");
  });
};

const tabs = ref([
  { name: SessionUser.objects.collectedOrderInvoices.meta.title, slot: 'collectedOrderInvoices', icon: 'fas fa-file-invoice-dollar', hidden: false },
  { name: SessionUser.objects.global.language.add + ' ' + SessionUser.objects.collectedOrderInvoices.meta.labels.single.toLowerCase(), slot: 'createNewInvoiceCollection', icon: 'fas fa-plus', hidden: false },
]);


</script>

<template>
  <div class="modal is-active" ref="modal">
    <div class="modal-background" @click="closeModal"></div>
    <div class="modal-card" style="width: 90%!important;">
      <header class="modal-card-head">
        <p class="modal-card-title">{{SessionUser.objects.global.language.select}} {{SessionUser.objects.global.language.invoice.toLowerCase()}} ( {{props.customer_id}} )</p>
        <button class="delete" aria-label="close" @click="closeModal"></button>
      </header>
      <section class="modal-card-body">
        <div class="content">
          <!-- Create a new invoice collection form -->
          <!-- Date: 2023-10-01 -->
          <ElementTabsBox
              v-bind:tabs="tabs"
              v-bind:default-active-tab="tabs[0].slot"
              v-bind:allow-compact-when-one-tab="true"
              >
            <template #collectedOrderInvoices>
              <!-- Invoice Collections table -->
              <CollectedOrderInvoicesPagination
                  v-bind:set-customer-filter="props.customer_id"
                  :table-props="{
                showEmpty: true,
                showTotal: false,
                isSelector: true,
                onSelected: props.onInvoiceCollectionSelected,
              }"
                  :display-booked="false"
              />

            </template>
            <template #createNewInvoiceCollection>
              <!-- Date picker -->
              <div class="field">
                <label class="label">{{SessionUser.objects.global.language.select}} {{SessionUser.objects.global.language.invoice.toLowerCase()}} {{SessionUser.objects.global.language.time.date.toLowerCase()}}</label>
                <div class="control">
                  <input class="input" type="date" v-model="selectedDate" />
                </div>
              </div>
              <!-- Create invoice collection button -->
              <div class="has-text-centered">
                <button class="button is-primary" @click="onClickCreateNewInvoiceCollection" :disabled="!selectedDate">
                  <span class="icon"><i class="fas fa-plus"></i></span>
                  <span>{{SessionUser.objects.global.language.add}} {{SessionUser.objects.collectedOrderInvoices.meta.labels.single.toLowerCase()}}</span>
                </button>
              </div>
            </template>
          </ElementTabsBox>
        </div>
      </section>
      <footer class="modal-card-foot">
        <!-- -->
      </footer>
    </div>
  </div>
</template>

<style scoped>

</style>