<script setup lang="ts">
import type { Page, PageRequest } from '@/api/pagination'
import { getSelectedProfile } from '@/api/profile'
import { TransactionApiClient, type TransactionsListItem } from '@/api/transaction'
import AppButton from '@/components/common/AppButton.vue'
import HomeModule from '@/components/HomeModule.vue'
import PaginationControls from '@/components/common/PaginationControls.vue'
import { onMounted, ref, type Ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import TransactionCard from '@/components/TransactionCard.vue'

const router = useRouter()
const route = useRoute()
const transactions: Ref<Page<TransactionsListItem>> = ref({
  items: [],
  pageRequest: { page: 1, size: 5, sorts: [] },
  totalElements: 0,
  totalPages: 0,
  isFirst: true,
  isLast: true,
})

onMounted(async () => {
  await fetchPage(transactions.value.pageRequest)
})

async function fetchPage(pageRequest: PageRequest) {
  const api = new TransactionApiClient(getSelectedProfile(route))
  try {
    transactions.value = await api.getTransactions(pageRequest)
  } catch (err) {
    console.error(err)
  }
}

function goToSearch() {
  router.push(`/profiles/${getSelectedProfile(route)}/transactions/search`)
}
</script>
<template>
  <HomeModule title="Transactions">
    <template v-slot:default>
      <PaginationControls
        :page="transactions"
        @update="(pr) => fetchPage(pr)"
        class="align-right"
      />
      <TransactionCard
        v-for="tx in transactions.items"
        :key="tx.id"
        :tx="tx"
      />
      <p v-if="transactions.totalElements === 0">You haven't added any transactions.</p>
    </template>
    <template v-slot:actions>
      <AppButton
        icon="plus"
        @click="router.push(`/profiles/${getSelectedProfile(route)}/add-transaction`)"
      >
        Add Transaction</AppButton
      >
      <AppButton @click="goToSearch()">Search</AppButton>
    </template>
  </HomeModule>
</template>
