<script setup>
import dayjs from "dayjs";

definePageMeta({
  middleware: "auth"
})
const dataStore = useDataStore()
const route = useRoute()
const supabase = useSupabaseClient()


const searchString = ref("")
const showAssigned = ref(false)
const selectedAccount = ref(0)

const filteredRows = computed(() => {
  let statements = dataStore.bankStatements

  if(!showAssigned.value) {
    statements = statements.filter(statement => !statement.customerInvoice || !statement.vendorInvoice)
  }

  if(selectedAccount.value !== 0) {
    statements = statements.filter(statement => statement.account === selectedAccount.value)
  }

  if(searchString.value.length > 0) {
    statements = statements.filter(item => {
      return Object.values(item).some((value) => {
        return String(value).toLowerCase().includes(searchString.value.toLowerCase())
      })
    })
  }

  return statements
})



const showStatementSlideover = ref(false)
const selectedStatement = ref({})

const selectStatement = (statement) => {
  selectedStatement.value = statement
  showStatementSlideover.value = true
}

const statementColumns = [
  {
    key:"amount",
    label: "Betrag"
  },
  {
    key:"date",
    label: "Datum",
    sortable: true
  },
  {
    key: "credName",
    label: "Empfänger"
  },
  {
    key: "debName",
    label: "Sender"
  },
  {
    key: "text",
    label: "Verwendungszweck"
  },
]

</script>

<template>
  <USlideover
    v-model="showStatementSlideover"
  >
    <UCard class="flex flex-col flex-1" :ui="{ body: { base: 'flex-1' }, ring: '', divide: 'divide-y divide-gray-100 dark:divide-gray-800' }">




      <DevOnly>
        {{selectedStatement}}
      </DevOnly>
    </UCard>

  </USlideover>

  <InputGroup :gap="2">
    <UInput
        v-model="searchString"
        placeholder="Suche..."
    />
    <USelectMenu
      :options="dataStore.bankAccounts.filter(account => account.used)"
      v-model="selectedAccount"
      option-attribute="iban"
      value-attribute="id"
    >
      <template #label>
        {{dataStore.bankAccounts.find(account => account.id === selectedAccount) ? dataStore.bankAccounts.find(account => account.id === selectedAccount).iban : "Kontoauswählen"}}
      </template>
    </USelectMenu>
    <UCheckbox
      v-model="showAssigned"
      label="Zugeordnete Anzeigen"
    />
  </InputGroup>

  <UTable
      :rows="filteredRows"
      :columns="statementColumns"
      @select="selectStatement"
    >
      <template #amount-data="{row}">
        <span
            v-if="row.amount >= 0"
            class="text-primary-500"
        >
          {{row.amount.toFixed(2) + " €"}}
        </span>
        <span
            v-if="row.amount < 0"
            class="text-rose-600"
        >
          {{row.amount.toFixed(2) + " €"}}
        </span>
      </template>
      <template #date-data="{row}">
        {{dayjs(row.date).format("DD.MM.YY")}}
      </template>
    </UTable>
</template>

<style scoped>

</style>