<template>
    <div class="flex items-center justify-between">
        <h1 class="text-4xl font-bold uppercase text-primary-500">Liste des fournisseurs</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="goToSupplier"
        >
            <template #header-name>
                <UiTextInput v-model="filters.name" placeholder="Nom" size="compact" />
            </template>
            <template #header-phone>
                <UiTextInput v-model="filters.phone" placeholder="Téléphone" size="compact" />
            </template>
            <template #header-email>
                <UiTextInput v-model="filters.email" placeholder="Mail" size="compact" />
            </template>
            <template #header-createdBy.username>
                <UiTextInput v-model="filters['createdBy.username']" placeholder="Créé par" 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/supplier"
            class="inline-flex items-center mb-16 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 { SupplierData } from '~/services/dto/supplier-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<SupplierData>(
        'suppliers',
        {
            name: '',
            phone: '',
            email: '',
            'createdBy.username': ''
        }
    )

const columns = [
    { key: 'name', label: 'Nom' },
    { key: 'phone', label: 'Téléphone' },
    { key: 'email', label: 'Mail' },
    { key: 'createdBy.username', label: 'Créé par' }
]

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

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

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