<script setup lang="ts">
import { formatMoney } from '@/api/data';
import type { Page, PageRequest } from '@/api/pagination';
import { TransactionApiClient, type TransactionsListItem } from '@/api/transaction';
import HomeModule from '@/components/HomeModule.vue';
import PaginationControls from '@/components/PaginationControls.vue';
import { useProfileStore } from '@/stores/profile-store';
import { onMounted, ref, type Ref } from 'vue';

const profileStore = useProfileStore()
const transactions: Ref<Page<TransactionsListItem>> = ref({ items: [], pageRequest: { page: 1, size: 10, sorts: [] }, totalElements: 0, totalPages: 0, isFirst: true, isLast: true })

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

async function fetchPage(pageRequest: PageRequest) {
  if (!profileStore.state) return
  const api = new TransactionApiClient(profileStore.state)
  try {
    transactions.value = await api.getTransactions(pageRequest)
  } catch (err) {
    console.error(err)
  }
}
</script>
<template>
  <HomeModule title="Transactions">
    <template v-slot:default>
      <table>
        <thead>
          <tr>
            <th>Date</th>
            <th>Amount</th>
            <th>Currency</th>
            <th>Description</th>
            <th>Credited Account</th>
            <th>Debited Account</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="tx in transactions.items" :key="tx.id">
            <td>
              {{ new Date(tx.timestamp).toLocaleDateString() }}
            </td>
            <td style="text-align: right;">{{ formatMoney(tx.amount, tx.currency) }}</td>
            <td>{{ tx.currency.code }}</td>
            <td>{{ tx.description }}</td>
            <td>{{ tx.creditedAccount?.name }}</td>
            <td>{{ tx.debitedAccount?.name }}</td>
            <td>
              <RouterLink :to="`/profiles/${profileStore.state?.name}/transactions/${tx.id}`">View</RouterLink>
            </td>
          </tr>
        </tbody>
      </table>
      <PaginationControls :page="transactions" @update="pr => fetchPage(pr)"></PaginationControls>
    </template>
  </HomeModule>
</template>
