<template>
    <div class="flex flex-col md:flex-row justify-between items-center space-y-3 md:space-y-0">
        <div class="text-sm text-gray-600" v-text="desc"></div>
        <div v-if="modelValue.last_page > 1" class="items-center flex space-x-2">
            <div class="hidden sm:flex text-gray-600 text-sm" v-text="pages"></div>
            <button
                v-if="modelValue.current_page !== 1"
                href="#"
                class="rounded !ml-0 sm:!ml-2 flex w-6 h-6 items-center justify-center leading-none shadow bg-blue-700 hover:bg-blue-600 items-center justify-center"
                @click.prevent="goto(modelValue.current_page - 1)"
            >
                <chevron class="rotate-90 text-white w-2 h-2"></chevron>
            </button>
            <button
                v-for="(button, index) in pageButtons"
                :key="index"
                href="#"
                class="rounded text-sm w-6 h-6 text-white flex items-center justify-center leading-none shadow"
                :class="{'bg-blue-500': button.current, 'bg-blue-700 hover:bg-blue-600': !button.current}"
                @click.prevent="goto(button.page)"
                v-text="button.page"
            ></button>
            <button
                v-if="modelValue.current_page !== modelValue.last_page"
                href="#"
                class="flex rounded text-sm w-6 h-6 items-center justify-center leading-none shadow bg-blue-700 hover:bg-blue-600 items-center justify-center"
                @click.prevent="goto(modelValue.current_page + 1)"
            >
                <chevron class="-rotate-90 text-white w-2 h-2"></chevron>
            </button>
        </div>
    </div>
</template>

<script setup>
import {computed} from 'vue';
import Chevron from './icons/Chevron.vue';
const emits = defineEmits(['reload']);

const props = defineProps({
    modelValue: {
        required: true,
    },
});

function goto(page) {
    if (page === props.modelValue.current_page) {
        return;
    }

    emits('reload', page);
}

const pageButtons = computed(() => {
    var from = Math.max(1, props.modelValue.current_page - 2);
    var to = Math.min(props.modelValue.last_page, props.modelValue.current_page + 2);

    return Array(to + 1)
        .fill(0)
        .map((index, key) => key)
        .slice(from)
        .map((page) => {
            return {
                page: page,
                current: page === props.modelValue.current_page,
            };
        });
});

const pages = computed(() => `Seite ${props.modelValue.current_page} von ${props.modelValue.last_page}`);
const desc = computed(() => `${props.modelValue.from} - ${props.modelValue.to} von ${props.modelValue.total} Einträgen`);
</script>
