<template>
    <div class="flex items-center justify-between">
        <h1 class="text-3xl font-bold text-primary-500 uppercase">Liste des types bovins</h1>
        <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"
            @click="handleAddClick"
        >
            <Icon name="mdi:plus" size="28"  />
            Ajouter
        </NuxtLink>
    </div>
    <div v-if="auth.isAdmin" class="mt-6 border border-slate-200 mb-16">
        <div class="max-h-96 overflow-y-auto">
            <div
                class="sticky
                       grid grid-cols-2 gap-4
                       bg-slate-100 px-4 py-3
                       font-semibold uppercase
                       tracking-wide"
            >
                <div class="col-span-1">Nom</div>
                <div class="col-span-1">Code</div>
            </div>
            <div v-if="bovinList.length === 0" class="px-4 py-6 text-slate-400">
                Aucun type de bovin.
            </div>
            <div v-else>
                <div
                    v-for="bovin in bovinList"
                    :key="bovin.id"
                    class="grid grid-cols-2 border-t gap-4 px-4 py-2 hover:bg-slate-50 cursor-pointer"
                    @click="goToBovin(bovin.id)"
                >
                    <div class="col-span-1">{{ bovin.label }}</div>
                    <div class="col-span-1">{{ bovin.code }}</div>
                </div>
            </div>
        </div>
    </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>
</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>
