<script setup>

const route = useRoute()
const router = useRouter()

const itemInfo = ref(null)
const statementallocations = ref([])
const incominginvoices = ref([])
const currentAccountId = computed(() => String(route.params.id))
const sameAccount = (value) => String(value ?? "") === currentAccountId.value

const setup = async () => {
  itemInfo.value = (await useEntities("accounts").selectSpecial("*")).find(i => i.id === Number(route.params.id))
  statementallocations.value = (await useEntities("statementallocations").select("*, bankstatement(*)"))
      .filter((allocation) => sameAccount(allocation.account?.id || allocation.account))
  incominginvoices.value = (await useEntities("incominginvoices").select("*, vendor(*)"))
      .filter((invoice) => (invoice.accounts || []).some((account) => sameAccount(account.account?.id || account.account)))
}

setup()

const renderedAllocations = computed(() => {
  const statementRows = statementallocations.value.map((allocation) => ({
    ...allocation,
    type: "statementallocation",
    amount: Number(allocation.amount || 0)
  }))

  const incomingInvoiceRows = incominginvoices.value.flatMap((invoice) => {
    return (invoice.accounts || [])
        .filter((account) => sameAccount(account.account?.id || account.account))
        .map((account, index) => ({
          id: `${invoice.id}-${index}`,
          incominginvoiceid: invoice.id,
          type: "incominginvoice",
          amount: Number(account.amountGross || account.amountNet || 0),
          expense: invoice.expense
        }))
  })

  return [...statementRows, ...incomingInvoiceRows]
})

const saldo = computed(() => {
  let value = 0

  renderedAllocations.value.forEach(i => {
    if(i.incominginvoiceid) {
      if(i.expense) {
        value = value - i.amount
      } else {
        value += i.amount
      }
    } else {
      value += i.amount
    }
  })

  return value
})

</script>

<template>
  <UDashboardNavbar>
    <template #left>
      <UButton
          icon="i-heroicons-chevron-left"
          variant="outline"
          @click="router.back()/*router.push(`/standardEntity/${type}`)*/"
      >
        Zurück
      </UButton>
      <UButton
          icon="i-heroicons-chevron-left"
          variant="outline"
          @click="router.push(`/accounts`)"
      >
        Übersicht
      </UButton>
    </template>
    <template #center>
      <h1
          v-if="itemInfo"
          :class="['text-xl','font-medium']"
      >{{itemInfo ? `Buchungskonto: ${itemInfo.number} - ${itemInfo.label}`: '' }}</h1>
    </template>
  </UDashboardNavbar>
  <UDashboardPanelContent>
    <UTabs :items="[{label: 'Information'},{label: 'Buchungen'}]">
      <template #content="{item}">
        <UCard class="mt-5" v-if="item.label === 'Information'">
          <div class="text-wrap">
            <table class="w-full" v-if="itemInfo">
              <tr>
                <td>Nummer:</td>
                <td>{{itemInfo.number}}</td>
              </tr>
              <tr>
                <td>Name:</td>
                <td>{{itemInfo.label}}</td>
              </tr>
              <tr>
                <td>Anzahl:</td>
                <td>{{renderedAllocations.length}}</td>
              </tr>
              <tr>
                <td>Saldo:</td>
                <td>{{useCurrency(saldo)}}</td>
              </tr>
              <tr>
                <td>Beschreibung:</td>
                <td>{{itemInfo.description}}</td>
              </tr>

            </table>
          </div>
        </UCard>
        <UCard class="mt-5" v-if="item.label === 'Buchungen'">
          <EntityShowSubOwnAccountsStatements
              v-if="itemInfo"
              :item="itemInfo"
              top-level-type="accounts"
              platform="desktop"
          />
        </UCard>
      </template>
    </UTabs>
  </UDashboardPanelContent>
</template>

<style scoped>
td {
  border-bottom: 1px solid lightgrey;
  vertical-align: top;
  padding-bottom: 0.15em;
  padding-top: 0.15em;
}
</style>
