<script setup>
import { ref, computed } from 'vue'
import { getCollections } from './api.js'
import CollectionListElement from './CollectionListElement.vue'
import Pagination from './Pagination.vue'
import AddCollection from './AddCollection.vue'

const limit = 5
const pageNumber = ref(1)

const offset = computed(() => (pageNumber.value - 1) * limit)

const data = ref(null)
const error = ref(null)

let totalCollectionsNumber = computed(() =>
  typeof data != 'undefined' && data.value != null ? data.value['count'] : 0,
)
let pageTotal = computed(() => Math.ceil(totalCollectionsNumber.value / limit))

fetchData()

function fetchData() {
  getCollections(data, error, limit, offset.value)
}

function pageChange(newPageNumber) {
  pageNumber.value = newPageNumber
  data.value = null
  fetchData()
}
</script>

<template>
  <div>
    <div v-if="error">{{ $t('bookbrowser.error', { error: error.message }) }}</div>
    <div v-else-if="data">
      <AddCollection @created="fetchData" />
      <div class="collectionslist">
        <div class="my-2" v-for="collection in data.collections" :key="collection.id">
          <CollectionListElement v-bind="collection" />
        </div>
      </div>
      <Pagination
        :pageNumber="pageNumber"
        :pageTotal="pageTotal"
        maxItemDisplayed="11"
        @pageChange="pageChange"
      />
    </div>
    <div v-else>{{ $t('bookbrowser.loading') }}</div>
  </div>
</template>

<style scoped></style>
