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

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

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

async function fetchPage(pageRequest: PageRequest) {
  const api = new TransactionApiClient(getSelectedProfile(route))
  try {
    page.value = await api.getDrafts(pageRequest)
  } catch (err) {
    console.error(err)
  }
}
</script>
<template>
  <HomeModule title="Drafts">
    <template v-slot:default>
      <PaginationControls
        :page="page"
        @update="(pr) => fetchPage(pr)"
        class="align-right"
      />
      <TransactionDraftCard
        v-for="draft in page.items"
        :key="draft.id"
        :draft="draft"
      />
      <p v-if="page.totalElements === 0">There are no drafts.</p>
    </template>
  </HomeModule>
</template>
