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

      <li v-for="(link, n) in links as IMetaLinks[]" :key="n">
        <a class="pointer" :class="{
          'disabled': link.active || !link.url,
          'current': link.active,
        }" @click.prevent="setPage(link.active ? undefined : link.url)">{{
            link.label
          }}</a>
      </li>

      <li>
        <a class="next page-numbers pointer" :class="currentPage === totalPages || lastLink?.active ?'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 {calcEndIndexByStartIndex, calcStartIndexByPage} from "@/services/calcPageService";
import type {IMeta} from "@/types/meta-d-t";
import type {IMetaLinks} from "@/types/meta-links-d-t";

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

type ItemDataType<T> = {
  data: T[];
  itemsPerPage: number;
  total?: number;
  meta?: IMeta;
};
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 links = computed(() =>
    (props.meta?.links || []).slice(1, -1)
);
const firstLink = computed(() => (props.meta?.links || [])?.[0]);
const lastLink = computed(() => (props.meta?.links || [])?.[props.meta?.links?.length - 1]);

const setPage = (idx?: string|number) => {
  if (typeof idx === 'number') {
    if (idx <= 0 || idx > Number(props?.meta?.last_page)) {
      return;
    }
  }
  if (!idx) {
    return;
  }

  scrollToTop();
  const query = {...route.query};
  if (typeof idx === 'string') {
    const q = (new URL(idx)).searchParams;
    currentPage.value = Number(q?.get('page')) || currentPage.value || 1;
    [...q].forEach(x => query[x[0]] = String(x[1]));
  } else {
    query.page = String(idx);
  }

  router.push({query});
  let startI = calcStartIndexByPage(currentPage.value, props.itemsPerPage);
  emit("handlePaginate", props.data, startI, calcEndIndexByStartIndex(startI, props.itemsPerPage));
};

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