<script setup>
import { ref, computed } from 'vue'
import { getMyBooks } from './api.js'
import BookListElement from './BookListElement.vue'
import Pagination from './Pagination.vue'

const FilterStates = Object.freeze({
  READ: 'read',
  WANTREAD: 'wantread',
  READING: 'reading',
})

const limit = 5
const pageNumber = ref(1)

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

let currentFilterState = ref(FilterStates.READ)

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

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

fetchData()

function fetchData() {
  let res = getMyBooks(data, error, currentFilterState.value, limit, offset.value)
}

function onFilterButtonClick(newstate) {
  currentFilterState.value = newstate
  pageNumber.value = 1
  fetchData()
}

function computeDynamicClass(state) {
  return currentFilterState.value === state ? 'is-active is-primary' : ''
}

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

<template>
  <div class="mb-5">
    <button
      class="button is-medium"
      @click="onFilterButtonClick(FilterStates.READ)"
      :class="computeDynamicClass(FilterStates.READ)"
    >
      {{ $t('bookbrowser.read') }}
    </button>
    <button
      class="button is-medium"
      @click="onFilterButtonClick(FilterStates.READING)"
      :class="computeDynamicClass(FilterStates.READING)"
    >
      {{ $t('bookbrowser.reading') }}
    </button>
    <button
      class="button is-medium"
      @click="onFilterButtonClick(FilterStates.WANTREAD)"
      :class="computeDynamicClass(FilterStates.WANTREAD)"
    >
      {{ $t('bookbrowser.wantread') }}
    </button>
  </div>
  <div v-if="error">{{ $t('bookbrowser.error', { error: error.message }) }}</div>
  <div v-else-if="data">
    <div class="">
      <div class="" v-for="book in data.books" :key="book.id">
        <BookListElement v-bind="book" />
      </div>
    </div>
    <Pagination
      :pageNumber="pageNumber"
      :pageTotal="pageTotal"
      maxItemDisplayed="11"
      @pageChange="pageChange"
    />
  </div>
  <div v-else>{{ $t('bookbrowser.loading') }}</div>
</template>

<style scoped>
.books {
  position: relative;
  float: left;
  width: 100%;
  height: auto;
  padding-bottom: 100px;
  line-height: 2.5;

  column-count: 2;
  column-gap: 15px;
}

#book {
  width: 100% !important;
  height: auto !important;
  transition: ease-in-out 0.15s;
}
</style>
