<template>
    <div class="flex items-center justify-between">
        <h1 class="text-3xl font-bold uppercase text-primary-500">Liste des fournisseurs</h1>
        <NuxtLink
            to="/admin/supplier"
            class="inline-flex items-center justify-center gap-2 text-xl uppercase bg-primary-500 text-white h-[50px] px-8 rounded"
            :class="auth.isAdmin ? '' : 'cursor-not-allowed opacity-60'"
            @click="handleAddClick"
        >
            <Icon name="mdi:plus" size="28"  />
            Ajouter
        </NuxtLink>
    </div>

    <UiDataTable
        v-if="auth.isAdmin"
        :columns="columns"
        url="suppliers"
        @row-click="onSupplierRowClick"
    />
    <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 type { ColumnConfig, Row } from "~/services/datatable"
import {formatAddresses} from "~/utils/datatable-formatters"
import { useAuthStore } from "~/stores/auth"

definePageMeta({ layout: "default" })

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

const columns: ColumnConfig[] = [
    { key: "name", label: "Nom" },
    { key: "email", label: "Mail" },
    { key: "addresses", label: "Adresses",  format: formatAddresses },
]

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

const onSupplierRowClick = (row: Row) => {
    const id = Number(row.id)
    if (!Number.isFinite(id)) return
    goToSupplier(id)
}

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

</script>
