<script setup>
import { ref, computed } from 'vue'
import BookListElement from './BookListElement.vue'
import { getSearchBooks, getAuthorBooks } from './api.js'
import { onBeforeRouteUpdate } from 'vue-router'
import Pagination from './Pagination.vue'

const limit = 5
const pageNumber = ref(1)

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

const props = defineProps({
  searchterm: String,
  authorId: Number,
})

const forceSearchInventaire = ref(false)

const searchInventaire = computed(() => {
  return forceSearchInventaire.value || (data.value !== null && data.value['inventaire'])
})

let data = ref(null)
let error = ref(null)

const pageTotal = computed(() => {
  const countValue = data.value !== null ? data.value['count'] : 0
  return Math.ceil(countValue / limit)
})

fetchData(props.searchterm, props.authorId)

function fetchData(searchTerm, authorId) {
  data.value = null
  error.value = null
  if (searchTerm != null) {
    const lang = navigator.language.substring(0, 2)
    getSearchBooks(
      data,
      error,
      searchTerm,
      lang,
      forceSearchInventaire.value ? 2 : 1,
      limit,
      offset.value,
    )
  } else if (authorId != null) {
    getAuthorBooks(data, error, authorId, limit, offset.value)
  }
}

onBeforeRouteUpdate(async (to, from) => {
  pageNumber.value = 1
  fetchData(to.params.searchterm, props.authorId)
})

function pageChange(newPageNumber) {
  pageNumber.value = newPageNumber
  data.value = null
  fetchData(props.searchterm, props.authorId)
}

function toggleSearchInventaire() {
  pageNumber.value = 1
  forceSearchInventaire.value = !forceSearchInventaire.value
  fetchData(props.searchterm, props.authorId)
  window.scrollTo(0, 0)
}
</script>

<template>
  <div class="booksearch my-2">
    <h1 class="title" v-if="data && data.inventaire">{{ $t('searchbook.importinventaire') }}</h1>
    <div v-if="error">{{ $t('searchbook.error', { error: error.message }) }}</div>
    <div v-else-if="data && data.books && data.books.length > 0">
      <div class="booksearchlist" v-for="book in data.books" :key="book.id">
        <BookListElement v-bind="book" />
      </div>
      <div
        v-if="(!searchInventaire || forceSearchInventaire) && !authorId"
        class="box container clickable has-background-dark"
        @click="toggleSearchInventaire"
      >
        <div class="is-size-4">
          {{ searchInventaire ? $t('searchbook.backtosearch') : $t('searchbook.searchinventaire') }}
        </div>
      </div>
      <Pagination
        :pageNumber="pageNumber"
        :pageTotal="pageTotal"
        maxItemDisplayed="11"
        @pageChange="pageChange"
      />
    </div>
    <div v-else-if="data === null">{{ $t('searchbook.loading') }}</div>
    <div v-else>{{ $t('searchbook.noresult') }}</div>
  </div>
</template>

<style scoped></style>
