<template>
	<div class="pagination">
		<w-button
			v-if="showArrows"
			class="pagination__prev"
			icon="mdi mdi-chevron-left"
			bg-color="transparent"
			lg
			:disabled="pageNumber <= 1"
			@click="$emit('input', value - 1)"
		/>
		<w-button
			v-for="(i, j) in visiblePages"
			:key="j"
			bg-color="accent-1"
			class="pagination__btn"
			:class="buttonClass(i)"
			@click="$emit('input', i - 1)"
		>
			{{ i }}
		</w-button>
		<w-button
			v-if="showArrows"
			class="pagination__next"
			icon="mdi mdi-chevron-right"
			bg-color="transparent"
			lg
			:disabled="pageNumber >= total"
			@click="$emit('input', value + 1)"
		/>
	</div>
</template>

<script lang="ts">
import { range } from 'lodash';
import Vue from 'vue';

export default Vue.extend({
	name: 'Pagination',
	props: {
		value: {
			type: Number,
			required: true
		},
		total: {
			type: Number,
			required: true
		},
		visible: {
			type: Number,
			default: 5
		},
		showArrows: {
			type: Boolean,
			default: true
		}
	},

	computed: {
		pageNumber(): number {
			return this.value + 1;
		},
		visiblePages(): number[] {
			if(this.visible % 2 == 0) {
				throw new Error('visible must be odd');
			}

			const amount = Math.max(Math.min(this.total, this.visible), 1);
			const offset = Math.floor(amount / 2);

			return range(
				Math.min(Math.max(this.pageNumber - offset, 1), this.total - amount + 1),
				Math.min(Math.max(this.pageNumber + offset, amount), this.total) + 1
			);
		}
	},

	methods: {
		buttonClass(i: number): any {
			return i == this.pageNumber || !this.total
				? 'pagination__btn--active'
				: undefined;
		}
	}
});
</script>

<style lang="scss">
.pagination {
	display: flex;
	justify-content: center;

	&__prev, &__next {
		@include margin(1, x);
		@include rounded(full);

		width: 2rem;
		height: 2rem;

	}

	&__btn {
		@include font-weight(semibold);
		@include font-size(xs);
		@include rounded(full);
		@include margin(1, x);

		background-color: var(--color-shade-2);
		color: var(--color-negative-1);
		height: 1.75rem;
		width: 1.75rem;

		&--active {
			background-color: var(--color-accent-1);
			color: white;
		}
	}
}
</style>