<script setup>

const createddocuments = ref([])
const bankaccounts = ref([])
const selected = ref([])
const selectedBankaccount = ref(null)
const loading = ref(true)
const toast = useToast()
const router = useRouter()

const setup = async () => {
  loading.value = true
  const [documents, accounts] = await Promise.all([
    useEntities("createddocuments").select("*, customer(id,name), outgoingsepamandate(*, bankaccount(*)), statementallocations(*)"),
    useEntities("bankaccounts").select("*")
  ])

  createddocuments.value = documents.filter(i => i.payment_type === "direct-debit" && i.outgoingsepamandate)
  bankaccounts.value = accounts.filter(i => !i.archived && !i.expired)
  selected.value = createddocuments.value
  selectedBankaccount.value = bankaccounts.value[0]?.id || null
  loading.value = false
}

setup()

const createExport = async () => {
  if (!selectedBankaccount.value) {
    toast.add({ title: "Bitte wählen Sie ein Gläubigerkonto aus.", color: "error" })
    return
  }

  if (!selected.value.length) {
    toast.add({ title: "Bitte wählen Sie mindestens einen Beleg aus.", color: "error" })
    return
  }

  //NUMMERN MAPPEN ZU IDS UND AN BACKEND FUNKTION ÜBERGEBEN
  const ids = selected.value.map((i) => i.id)

  const res = await useNuxtApp().$api("/api/exports/sepa", {
    method: "POST",
    body: {
      idsToExport: ids,
      creditorBankaccountId: selectedBankaccount.value
    }
  })

  if (res.success) {
    toast.add({ title: "SEPA-Export wird erstellt. Sie finden die Datei anschließend in der Exportliste." })
    await router.push("/export")
  } else {
    toast.add({ title: res.message || "Der SEPA-Export konnte nicht gestartet werden.", color: "error" })
  }

}


</script>

<template>
  <UDashboardNavbar title="SEPA Export erstellen">
    <template #right>
      <UButton @click="createExport">
        Erstellen
      </UButton>
    </template>
  </UDashboardNavbar>
  <div class="p-4">
    <UFormField label="Gläubigerkonto" class="max-w-xl">
      <USelectMenu
          v-model="selectedBankaccount"
          value-key="id"
          label-key="name"
          :items="bankaccounts"
          :search-input="{ placeholder: 'Konto suchen...' }"
          :filter-fields="['name', 'iban', 'bankId']"
          class="w-full"
      >
        <template #default>
          {{ bankaccounts.find(i => i.id === selectedBankaccount)?.name || "Gläubigerkonto auswählen" }}
        </template>
        <template #item="{ item }">
          {{ item.name || item.ownerName || "Bankkonto" }} - {{ item.iban }} - {{ item.bankId }}
        </template>
      </USelectMenu>
    </UFormField>
  </div>
  <UTable
      :loading="loading"
      v-model="selected"
      :loading-state="{ icon: 'i-heroicons-arrow-path-20-solid', label: 'Loading...' }"
      :data="createddocuments"
      :columns="normalizeTableColumns([
        { key: 'documentNumber', label: 'Belegnummer' },
        { key: 'customer', label: 'Kunde' },
        { key: 'documentDate', label: 'Belegdatum' },
        { key: 'outgoingsepamandate', label: 'SEPA-Mandat' },
      ])"
      :empty="{ icon: 'i-heroicons-circle-stack-20-solid', label: 'Keine SEPA-Belege anzuzeigen' }"
  >
    <template #customer-cell="{ row }">
      {{ row.original.customer?.name || "-" }}
    </template>
    <template #outgoingsepamandate-cell="{ row }">
      {{ row.original.outgoingsepamandate?.reference || "-" }}
    </template>
  </UTable>
</template>

<style scoped>

</style>
