<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 class="mt-7 border border-slate-200 mb-11 ">
        <div class="grid grid-cols-2 gap-4 text-primary-700 bg-slate-100 px-4 py-3 text-sm font-semibold uppercase tracking-wide">
            <div>Nom</div>
            <div>Code</div>
        </div>
        <div v-if="!auth.isAdmin" class="px-4 py-6 text-slate-400">
            Accès réservé aux administrateurs.
        </div>
        <div v-else-if="bovinList.length === 0" class="px-4 py-6 text-slate-400">
            Aucun type de bovin.
        </div>
        <template v-else>
            <div
                v-for="bovin in bovinList"
                :key="bovin.id"
                class="grid grid-cols-2 text-primary-700 gap-4 px-4 py-3 text-sm hover:bg-slate-50 cursor-pointer border-t border-slate-200"
                role="button"
                tabindex="0"
                @click="goToBovin(bovin.id)"
                @keydown.enter="goToBovin(bovin.id)"
            >
                <div>{{ bovin.label }}</div>
                <div>{{ bovin.code }}</div>
            </div>
        </template>
    </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 { getBovineTypeList } from "~/services/bovine-type"
import type { BovineTypeData } from "~/services/dto/bovine-type-data"
import { useAuthStore } from "~/stores/auth"

const bovinList = ref<BovineTypeData[]>([])
const router = useRouter()
const auth = useAuthStore()

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

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

onMounted(async () => {
    if (!auth.isAdmin) return
    bovinList.value = await getBovineTypeList()
})
</script>
