<script setup>
import BaseButton from "../../../components/base/BaseButton.vue";
import BaseIndex from "../../../components/base/BaseIndex.vue";
import B2CDataTable from "../../../components/common/B2CDataTable.vue";
import { nextTick, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { useInvoiceList } from "../composables/useInvoices.js";
import { fetchInvoicePdfBlob } from "../composables/useInvoices.js";

const router = useRouter();

const {
  rows,
  totalRecords,
  totalAllRecords,
  loading,
  error,
  pagination,
  sort,
  load,
  onTableState,
} = useInvoiceList();

const columns = [
  {
    key: "document_number",
    header: "Nr.",
    type: "text",
    searchable: true,
    filterable: true,
    sortable: true,
  },
  {
    key: "type",
    header: "Type",
    type: "text",
    searchable: false,
    filterable: true,
    sortable: false,
  },
  {
    key: "customer_name",
    header: "Klant",
    type: "text",
    searchable: true,
    filterable: false,
    sortable: false,
  },
  {
    key: "invoice_date",
    header: "Factuurdatum",
    type: "date",
    searchable: false,
    filterable: false,
    sortable: true,
  },
  {
    key: "total_inc_vat",
    header: "Totaal (incl. btw)",
    type: "text",
    searchable: false,
    filterable: false,
    sortable: true,
  },
  {
    key: "status",
    header: "Status",
    type: "text",
    searchable: false,
    filterable: true,
    sortable: true,
  },
];

async function openPdf(row) {
  try {
    const blob = await fetchInvoicePdfBlob(row.id);
    const url = URL.createObjectURL(blob);
    window.open(url, "_blank", "noopener");
    setTimeout(() => URL.revokeObjectURL(url), 60_000);
  } catch {
    /* toast optional */
  }
}

onMounted(async () => {
  await nextTick();
  await load();
});
</script>

<template>
  <BaseIndex flush hide-header>
    <B2CDataTable
      table-key="invoices.index"
      :columns="columns"
      :rows="rows"
      :loading="loading"
      server-mode
      :total-records="totalRecords"
      :total-all-records="totalAllRecords"
      :pagination="pagination"
      :sort="sort"
      :persist-to-server="true"
      search-placeholder="Zoeken…"
      :table-error="error"
      :rows-per-page-options="[10, 15, 25, 50]"
      :rows-per-page="15"
      :paginator="true"
      :enable-export="false"
      row-clickable
      resource-label-singular="invoice"
      resource-label-plural="invoices"
      show-actions
      @row-click="
        ({ data }) =>
          router.push({ name: 'invoices-edit', params: { id: String(data.id) } })
      "
      @update:pagination="
        pagination = $event;
        load();
      "
      @update:sort="
        sort = $event;
        load();
      "
      @update:state="onTableState($event)"
    >
      <template #toolbar-title>
        <div>
          <h1
            class="text-2xl font-semibold tracking-tight text-surface-950 dark:text-surface-0 m-0"
          >
            Facturen
          </h1>
          <p
            class="text-sm text-surface-600 dark:text-surface-400 mt-1.5 mb-0 max-w-3xl"
          >
            Facturen en creditnota’s (EUR, per kalenderjaar genummerd).
          </p>
        </div>
      </template>
      <template #controls-left>
        <BaseButton
          variant="primary"
          icon="plus"
          label="Nieuwe factuur"
          class="shrink-0"
          @click="router.push({ name: 'invoices-new' })"
        />
        <BaseButton
          variant="secondary"
          icon="plus"
          label="Creditnota"
          class="shrink-0"
          @click="router.push({ name: 'invoices-credit-new' })"
        />
      </template>

      <template #actions="{ row }">
        <div class="flex flex-nowrap items-center justify-end gap-1">
          <BaseButton
            v-if="row.status === 'finalized'"
            variant="secondary"
            icon="file"
            text
            rounded
            size="small"
            class="shrink-0"
            :iconOnly="true"
            aria-label="PDF"
            @click.stop="openPdf(row)"
          />
          <BaseButton
            variant="secondary"
            icon="pencil"
            text
            rounded
            size="small"
            class="shrink-0"
            :iconOnly="true"
            aria-label="Bewerken"
            @click.stop="
              router.push({
                name: 'invoices-edit',
                params: { id: String(row.id) },
              })
            "
          />
        </div>
      </template>
    </B2CDataTable>
  </BaseIndex>
</template>
