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

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

const bankaccounts = ref([])

const setupPage = async () => {
  if(route.query.ref) {
    reqData.value = await useFunctions().useBankingListRequisitions(route.query.ref)
  }

  bankaccounts.value = await useSupabaseSelect("bankaccounts")
}

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

const generateLink = async (bankId) => {
  try {
    /*const {data,error} = await supabase.functions.invoke(`bankstatement_gateway`,{
      body: {
        method: "generateLink",
        institutionId: bankData.value.id,
        tenant: profileStore.currentTenant
      }
    })*/
    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
    }

    const {data,error} = await supabase.from("bankaccounts").insert(accountData).select()
    if(error) {
      toast.add({title: "Es gab einen Fehler bei hinzufügen des Accounts", color:"rose"})
    } else if(data) {
      toast.add({title: "Account erfolgreich hinzugefügt"})
    }
}

const updateAccount = async (account) => {
    const {data,error} = await supabase.from("bankaccounts").update({accountId: account.id, expired: false}).eq("iban",account.iban).select()
    if(error) {
      console.log(error)
      toast.add({title: "Es gab einen Fehler bei aktualisieren des Accounts", color:"rose"})
    } else if(data) {
      toast.add({title: "Account erfolgreich aktualisiert"})
      setupPage()
    }
}

setupPage()
</script>

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

          <UFormGroup
            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>

          </UFormGroup>
          <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="rose"
            variant="outline"
            class="mt-3"
          />

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

  <div
      v-for="account in reqData.accounts"
      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)"
    >
      + Konto
    </UButton>
    <UButton
      @click="updateAccount(account)"
      v-else
    >
      Aktualisieren
    </UButton>
  </div>

<!--  <UButton @click="setupPage">Setup</UButton>
  <div v-if="route.query.reqId">
    {{reqData}}
  </div>-->

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

</template>

<style scoped>

</style>