<template>
    <div class="px-[86px]">
        <div class="flex items-center justify-between">
            <h1 class="text-4xl font-bold uppercase text-primary-500">Liste des types bovins</h1>
            <NuxtLink
                v-if="auth.isAdmin"
                to="/admin/bovin"
                class="inline-flex items-center justify-center text-xl text-white uppercase bg-primary-500 h-[50px] px-6 rounded hover:opacity-80 gap-2"
            >
                <Icon name="mdi:plus" size="28" />
                Ajouter
            </NuxtLink>
        </div>

        <div v-if="auth.isAdmin" class="mt-6 mb-16">
            <UiDataTable
                v-model:page="page"
                v-model:per-page="perPage"
                :columns="columns"
                :items="items"
                :total-items="totalItems"
                :loading="loading"
                row-clickable
                @row-click="goToBovin"
            >
                <template #header-label>
                    <UiTextInput v-model="filters.label" placeholder="Nom" size="compact" />
                </template>
                <template #header-code>
                    <UiTextInput v-model="filters.code" placeholder="Code" size="compact" />
                </template>
            </UiDataTable>
        </div>
        <div v-else class="mt-6 border border-slate-200 mb-16 px-4 py-6 text-slate-400">
            Accès réservé aux administrateurs.
        </div>
    </div>
</template>

<script setup lang="ts">
import type { BovineTypeData } from '~/services/dto/bovine-type-data'
import { useAuthStore } from '~/stores/auth'
import { useDataTableServerState } from '~/composables/useDataTableServerState'

const router = useRouter()
const auth = useAuthStore()

const { items, totalItems, page, perPage, filters, loading, reload } =
    useDataTableServerState<BovineTypeData>(
        'bovine_types',
        {
            label: '',
            code: ''
        }
    )

const columns = [
    { key: 'label', label: 'Nom' },
    { key: 'code', label: 'Code' }
]

const goToBovin = (bovin: BovineTypeData) => {
    if (!auth.isAdmin) return
    router.push(`/admin/bovin/${bovin.id}`)
}

onMounted(() => {
    if (auth.isAdmin) reload()
})
</script>
