<template>
  <nav>
    <ul>
      <li>
        <a class="tp-pagination-prev prev page-numbers pointer" :class="currentPage === 1 ?'disabled':''" @click.prevent="setPage(currentPage-1)">
          <svg-paginate-prev />
        </a>
      </li>

      <li v-for="n in totalPages" :key="n">
        <a :class="`pointer ${currentPage === n ? 'current disabled' : ''}`" @click.prevent="setPage(n)">{{
            n
          }}</a>
      </li>

      <li>
        <a class="next page-numbers pointer" :class="currentPage === totalPages ?'disabled':''" @click.prevent="setPage(currentPage+1)">
          <svg-paginate-next />
        </a>
      </li>
    </ul>
  </nav>
</template>

<script lang="ts" setup>
import {computed, onMounted, ref, watch} from "vue";
import {calcStartIndexByPage} from "@/services/calcPageService";

const emit = defineEmits(["handlePaginate"]);
const route = useRoute();
const router = useRouter();

type ItemDataType<T> = {
  data: T[];
  itemsPerPage: number;
  total?: number
};
const props = defineProps<ItemDataType<any>>();
const currentPage = ref<number>(Number(route?.query?.page || 1));
const totalPages = computed(() =>
    (props?.total ? Math.ceil(props.total / props.itemsPerPage) : 0) || Math.ceil(props.data.length / props.itemsPerPage)
);
const startIndex = computed(() => calcStartIndexByPage(currentPage.value, props.itemsPerPage));
const endIndex = computed(() => startIndex.value + props.itemsPerPage);

const setPage = (idx: number) => {
  debugger
  if (idx <= 0 || idx > totalPages.value) {
    return;
  }

  if (currentPage.value === idx)
  {
    return false;
  }
    scrollToTop();
  currentPage.value = idx;
  const query = {...route.query, page: String(idx)};
  router.push({query});
  emit("handlePaginate", props.data, startIndex.value, endIndex.value);
};

onMounted(() => {
  emit("handlePaginate", props.data, startIndex.value, endIndex.value);
});
watch(
    () => route.query || route.params,
    (newStatus) => {
      currentPage.value = Number(route?.query?.page || 1);
    }
);
</script>
