<template>
	<ul class="wcc-pagination">
		<li class="wcc-pagination-item">
			<button
				type="button"
				@click="changePage(1)"
				:disabled="isInFirstPage"
				aria-label="Go to first page"
				class="wcc-button wcc-pagination-button"
			>
				«
			</button>
		</li>

		<li class="wcc-pagination-item">
			<button
				type="button"
				@click="changePage(currentPage - 1)"
				:disabled="isInFirstPage"
				aria-label="Go to previous page"
				class="wcc-button wcc-pagination-button"
			>
				‹
			</button>
		</li>

		<li v-for="page in pages" :key="page.name" class="wcc-pagination-item">
			<button
				type="button"
				@click="changePage(page.name)"
				:disabled="page.isDisabled"
				class="wcc-button wcc-pagination-button wcc-pagination-number"
				:class="{ active: isPageActive(page.name) }"
				:aria-label="`Go to page number ${page.name}`"
			>
				{{ page.name }}
			</button>
		</li>

		<li class="wcc-pagination-item">
			<button
				type="button"
				@click="changePage(currentPage + 1)"
				:disabled="isInLastPage"
				aria-label="Go to next page"
				class="wcc-button wcc-pagination-button"
			>
				›
			</button>
		</li>

		<li class="wcc-pagination-item">
			<button
				type="button"
				@click="changePage(totalPages)"
				:disabled="isInLastPage"
				aria-label="Go to last page"
				class="wcc-button wcc-pagination-button"
			>
				»
			</button>
		</li>
	</ul>
</template>

<script>
export default {
	name: "Pagination",
	props: {
		maxVisibleButtons: {
			type: Number,
			required: false,
			default: 3,
		},
		total: {
			type: Number,
			required: true,
		},
		perPage: {
			type: Number,
			required: true,
		},
		currentPage: {
			type: Number,
			required: true,
		},
	},
	computed: {
		totalPages() {
			let totalPages = 1;
			totalPages = Math.ceil(this.total / this.perPage);
			return totalPages;
		},
		startPage() {
			if (this.currentPage === 1) {
				return 1;
			}

			if (this.currentPage === this.totalPages) {
				return this.totalPages - this.maxVisibleButtons + 1;
			}
			return this.currentPage - 1;
		},
		endPage() {
			return Math.min(
				this.startPage + this.maxVisibleButtons - 1,
				this.totalPages
			);
		},
		pages() {
			const range = [];

			for (let i = this.startPage; i <= this.endPage; i += 1) {
				range.push({
					name: i,
					isDisabled: i === this.currentPage,
				});
			}

			return range;
		},
		isInFirstPage() {
			return this.currentPage === 1;
		},
		isInLastPage() {
			return this.currentPage === this.totalPages;
		},
	},
	methods: {
		changePage(page) {
			this.$emit("pagechanged", page);
		},
		isPageActive(page) {
			return this.currentPage === page;
		},
	},
};
</script>
<style lang="scss">
@include wrap-class() {
	.wcc-pagination {
		list-style-type: none;
		list-style: none;
		display: flex;
		justify-content: flex-end;
		padding: 15px;
		margin: 0;
	}
}
</style>
