<template>
  <TableListSecondary
    :headers="headers"
    :items="workOrders"
    :pages="pages"
    :page-range="pageRange"
    :loading="loading"
    :height="'calc(100vh - 177px)'"
    v-model:page="page"
    v-model="selected"
    @update:pagination="_getWorkOrders"
    @row-click="handleRowClick"
    @click:create="emit('click:create')"
    :length="pages"
  >
    <template #title>
      <span class="text-h6 font-weight-regular">Work Order</span>
    </template>
    <template #action-button>
      <v-btn
        color="primary-button"
        variant="flat"
        class="ml-4 text-capitalize"
        @click="emit('click:create')"
      >
        Work Order
      </v-btn>
    </template>

    <template #createdAt="{ item }">
      {{
        new Date(item.createdAt).toLocaleString("en-GB", {
          day: "2-digit",
          month: "2-digit",
          year: "numeric",
          hour: "2-digit",
          minute: "2-digit",
          hour12: false,
        })
      }}
    </template>

    <template #status="{ item }">
      <v-chip
        :color="getColorStatus(item.status || 'No Status')"
        text-color="white"
        variant="flat"
      >
        {{ item.status || "No Status" }}
      </v-chip>
    </template>
  </TableListSecondary>
</template>

<script lang="ts" setup>
const emit = defineEmits(["click:create", "update:pagination"]);

const { page, pages, pageRange, workOrders, getWorkOrders } = useWorkOrder();
const { getColorStatus } = useUtils();

const message = ref("");
const messageColor = ref("");
const messageSnackbar = ref(false);
const loading = ref(false);
const height = ref("500px");
const selected = ref<string[]>([]);

const headers = ref([
  { title: "Created By", value: "createdByName" },
  { title: "Subject", value: "subject" },
  { title: "Category", value: "application" },
  { title: "Status", value: "status" },
  { title: "Date", value: "createdAt" },
]);

async function _getWorkOrders() {
  loading.value = true;

  try {
    await getWorkOrders({
      page: page.value,
    });

    emit("update:pagination", {
      page: page.value,
      pages: pages.value,
    });
  } catch (error) {
    console.error("Error fetching feedbacks:", error);
  } finally {
    loading.value = false;
  }
}

_getWorkOrders();
</script>
