<script setup>
const dataStore = useDataStore()
const profileStore = useProfileStore()
const route = useRoute()
const router = useRouter()
const url = useRequestURL()
const toast = useToast()

const showAddBankRequisition = ref(false)
const bicBankToAdd = ref("")
const bankData = ref({})
const showAlert = ref(false)
const reqData = ref({})

const bankaccounts = ref([])

const showReqData = ref(false)

const setupPage = async () => {
  if(route.query.ref) {
    reqData.value = await useFunctions().useBankingListRequisitions(route.query.ref)
    if(reqData.value.accounts.length > 0){
      showReqData.value = true
    }
  }

  bankaccounts.value = await useEntities("bankaccounts").select()
}

const checkBIC = async () => {
  bankData.value = await useFunctions().useBankingCheckInstitutions(bicBankToAdd.value)
  showAlert.value = true
}

const generateLink = async (bankId) => {
  try {

    const link = await useFunctions().useBankingGenerateLink(bankId || bankData.value.id)

    await navigateTo(link, {
      open: {
        target: "_blank"
      }
    })
  } catch (error) {
    console.log(error)
  }
}

const addAccount = async (account) => {
  let accountData = {
    accountId: account.id,
    ownerName: account.owner_name,
    iban: account.iban,
    tenant: profileStore.currentTenant,
    bankId: account.institution_id
  }

  try {
    // Nutzung von useEntities statt direktem DB-Call
    // true als 2. Parameter verhindert den Redirect, da wir im Modal sind
    const res = await useEntities("bankaccounts").create(accountData, true)

    if(res) {
      // useEntities feuert bereits einen Success-Toast ("X hinzugefügt")
      // Wir laden die Seite neu, um die Buttons im Modal zu aktualisieren (Hinzufügen -> Aktualisieren)
      await setupPage()
    }
  } catch (error) {
    console.error(error)
    toast.add({title: "Es gab einen Fehler beim Hinzufügen des Accounts", color:"error"})
  }
}

const updateAccount = async (account) => {

  let bankaccountId = bankaccounts.value.find(i => i.iban === account.iban).id

  // Fehlerbehandlung analog zu addAccount verbessert
  try {
    const res = await useEntities("bankaccounts").update(bankaccountId, {accountId: account.id, expired: false}, true)

    // useEntities feuert bereits einen Success-Toast
    // reqData.value = null // Das würde das Modal leeren, ggf. gewünscht? Im Original war es drin.
    setupPage()
  } catch (error) {
    console.log(error)
    toast.add({title: "Es gab einen Fehler beim Aktualisieren des Accounts", color:"error"})
  }
}

setupPage()
</script>

<template>
  <UDashboardNavbar title="Bankkonten">
    <template #right>
      <UButton
          @click="showAddBankRequisition = true"
      >
        + Bankverbindung
      </UButton>
      <USlideover
          v-model:open="showAddBankRequisition"
      >
        <template #body>
          <UCard
              class="h-full"
          >
            <template #header>
              <p>Bankverbindung hinzufügen</p>
            </template>

          <UFormField
              label="BIC:"
              class="flex-auto"
          >
            <InputGroup class="w-full">
              <UInput
                  v-model="bicBankToAdd"
                  class="flex-auto"
                  @keydown.enter="checkBIC"
              />
              <UButton
                  @click="checkBIC"
              >
                Check
              </UButton>
            </InputGroup>

          </UFormField>
          <UAlert
              v-if="showAlert && bankData.id && bankData.countries.includes('DE')"
              title="Bank gefunden"
              icon="i-heroicons-check-circle"
              color="primary"
              variant="outline"
              class="mt-3"
              :actions="[{ variant: 'solid', color: 'primary', label: 'Verbinden',click: generateLink }]"
          />
            <UAlert
                v-else-if="showAlert && !bankData.id"
                title="Bank nicht gefunden"
                icon="i-heroicons-x-circle"
                color="error"
                variant="outline"
                class="mt-3"
            />

          </UCard>
        </template>
      </USlideover>
    </template>
  </UDashboardNavbar>

  <UModal v-model:open="showReqData">
    <template #content>
      <UCard>
        <template #header>
          Verfügbare Bankkonten
        </template>
        <div
            v-for="account in reqData.accounts"
            :key="account.id"
            class="p-2 m-3 flex justify-between"
        >
          {{account.iban}} - {{account.owner_name}}

          <UButton
              @click="addAccount(account)"
              v-if="!bankaccounts.find(i => i.iban === account.iban)"
          >
            Hinzufügen
          </UButton>
          <UButton
              @click="updateAccount(account)"
              v-else
          >
            Aktualisieren
          </UButton>
        </div>
      </UCard>
    </template>
  </UModal>

  <UTable
      :data="bankaccounts"
      :columns="normalizeTableColumns([
        {
          key: 'expired',
          label: 'Aktiv'
        },{
          key: 'iban',
          label: 'IBAN'
        },{
          key: 'bankId',
          label: 'Bank'
        },{
          key: 'ownerName',
          label: 'Kontoinhaber'
        },{
          key: 'balance',
          label: 'Saldo'
        },
      ])"
  >
    <template #expired-cell="{ row }">
      <span v-if="row.original.expired" class="text-error-600">Ausgelaufen</span>
      <span v-else class="text-primary">Aktiv</span>
      <UButton
          v-if="row.original.expired"
          variant="outline"
          class="ml-2"
          @click="generateLink(row.original.bankId)"
      >Aktualisieren</UButton>
    </template>
    <template #balance-cell="{ row }">
      {{ row.original.balance ? row.original.balance.toFixed(2).replace(".",",") + ' €' : '-' }}
    </template>
    <template #iban-cell="{ row }">
      {{ row.original.iban.match(/.{1,5}/g).join(" ") }}
    </template>
    <template #empty>
      <TableEmptyState label="Keine Bankkonten anzuzeigen" />
    </template>
  </UTable>

</template>

<style scoped>

</style>
