<template>
    <div class="flex items-center justify-between">
        <h1 class="text-4xl font-bold uppercase text-primary-500">Liste des types bovins</h1>
    </div>

    <div v-if="auth.isAdmin" class="mt-7 mb-11">
        <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-7 border border-slate-200 mb-11 px-4 py-6 text-slate-400">
        Accès réservé aux administrateurs.
    </div>

    <div class="flex justify-center items-center">
        <NuxtLink
            to="/admin/bovin"
            class="inline-flex items-center justify-center text-xl text-white uppercase bg-primary-500 h-[50px] px-8 rounded hover:opacity-80 gap-2"
            :class="auth.isAdmin ? '' : 'cursor-not-allowed opacity-60'"
            @click="handleAddClick"
        >
            <Icon name="mdi:plus" size="28" />
            Ajouter
        </NuxtLink>
    </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}`)
}

const handleAddClick = (event: Event) => {
    if (auth.isAdmin) return
    event.preventDefault()
}

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