<template>
    <div>
        <div class="flex items-center justify-between">
            <h2 class="text-lg font-bold text-neutral-900">Clients</h2>
            <button
                class="rounded-md bg-primary-500 px-4 py-2 text-sm font-semibold text-white hover:bg-secondary-500"
                @click="openCreate"
            >
                + Ajouter un client
            </button>
        </div>

        <DataTable
            :columns="columns"
            :items="clients"
            :loading="isLoading"
            empty-message="Aucun client trouvé."
            deletable
            @row-click="openEdit"
            @delete="(item) => handleDelete(item.id)"
        >
            <template #cell-email="{ item }">
                {{ item.email ?? '-' }}
            </template>
            <template #cell-address="{ item }">
                {{ formatAddress(item) }}
            </template>
            <template #cell-phone="{ item }">
                {{ item.phone ?? '-' }}
            </template>
        </DataTable>

        <ClientDrawer
            v-model="drawerOpen"
            :client="selectedClient"
            @saved="onSaved"
        />
    </div>
</template>

<script setup lang="ts">
import type { Client } from '~/services/dto/client'
import { useClientService } from '~/services/clients'

import type { DataTableColumn } from '~/components/ui/DataTable.vue'

const columns: DataTableColumn[] = [
    { key: 'name', label: 'Nom', primary: true },
    { key: 'email', label: 'Email', class: 'text-primary-500' },
    { key: 'address', label: 'Adresse', class: 'text-neutral-700' },
    { key: 'phone', label: 'Téléphone', class: 'text-primary-500' },
]

const { getAll, remove } = useClientService()
const clients = ref<Client[]>([])
const isLoading = ref(true)
const drawerOpen = ref(false)
const selectedClient = ref<Client | null>(null)

async function loadClients() {
    isLoading.value = true
    try {
        clients.value = await getAll()
    } finally {
        isLoading.value = false
    }
}

function openCreate() {
    selectedClient.value = null
    drawerOpen.value = true
}

function openEdit(client: Client) {
    selectedClient.value = client
    drawerOpen.value = true
}

function formatAddress(client: Client): string {
    return [client.street, client.postalCode, client.city]
        .filter(Boolean)
        .join(', ') || '-'
}

async function handleDelete(id: number) {
    await remove(id)
    await loadClients()
}

async function onSaved() {
    await loadClients()
}

onMounted(() => {
    loadClients()
})
</script>
