<template>
  <nav
    class="pagination mx-0"
    role="navigation"
    aria-label="pagination"
  >
    <ul
      class="pagination-list"
      v-if="pageInfo"
    >
      <li v-for="v in pageInfo">
        <a
          v-if="currentPage === v"
          class="pagination-link is-current has-background-primary has-text-white"
          :aria-label="`Page ${v}`"
          aria-current="page"
          >{{ v }}</a
        >
        <a
          v-else
          href="#"
          class="pagination-link"
          :aria-label="`Goto page ${v}`"
          @click="changePage(v)"
          >{{ v }}</a
        >
      </li>
      <a
        @click="previous()"
        class="pagination-previous ml-5"
      >
        <SvgIcon
          v-bind="{
            name: 'left1.svg',
            type: 'dark',
            size: 20,
            alt: 'Tìm kiếm',
          }"
        ></SvgIcon>
      </a>
      <a
        @click="next()"
        class="pagination-next"
      >
        <SvgIcon
          v-bind="{
            name: 'right.svg',
            type: 'dark',
            size: 20,
            alt: 'Tìm kiếm',
          }"
        ></SvgIcon>
      </a>
    </ul>
  </nav>
</template>
<script setup>
const emit = defineEmits(["changepage"]);
var props = defineProps({
  data: Array,
  perPage: Number,
});
var currentPage = 1;
var totalRows = props.data.length;
var lastPage = parseInt(totalRows / props.perPage);
if (lastPage * props.perPage < totalRows) lastPage += 1;
var pageInfo = ref();
function pages(current_page, last_page, onSides = 2) {
  // pages
  let pages = [];
  // Loop through
  for (let i = 1; i <= last_page; i++) {
    // Define offset
    let offset = i == 1 || last_page ? onSides + 1 : onSides;
    // If added
    if (i == 1 || (current_page - offset <= i && current_page + offset >= i) || i == current_page || i == last_page) {
      pages.push(i);
    } else if (i == current_page - (offset + 1) || i == current_page + (offset + 1)) {
      pages.push("...");
    }
  }
  return pages;
}
function changePage(page) {
  if (page === "...") return;
  currentPage = page;
  pageInfo.value = pages(page, lastPage, 2);
  emit("changepage", page);
}
pageInfo.value = pages(1, lastPage, 2);
watch(
  () => props.data,
  (newVal, oldVal) => {
    totalRows = props.data.length;
    lastPage = parseInt(totalRows / props.perPage);
    if (lastPage * props.perPage < totalRows) lastPage += 1;
    pageInfo.value = pages(1, lastPage, 2);
  },
);
function previous() {
  if (currentPage > 1) changePage(currentPage - 1);
}
function next() {
  if (currentPage < lastPage) changePage(currentPage + 1);
}
</script>
