<template>
    <div>
        <PageHeader>
            {{ t('admin.sites.title') }}
            <template #actions>
                <MalioButton
                    v-if="can('sites.manage')"
                    variant="secondary"
                    :label="t('admin.sites.newSite')"
                    icon-name="mdi:add-bold"
                    icon-position="left"
                    @click="openCreateDrawer"
                />
            </template>
        </PageHeader>

        <!-- Table des sites — pagination serveur via usePaginatedList (#73). -->
        <MalioDataTable
            :columns="columns"
            :items="siteItems"
            :total-items="totalItems"
            :page="currentPage"
            :per-page="itemsPerPage"
            :per-page-options="itemsPerPageOptions"
            :row-clickable="canManage"
            :empty-message="t('admin.sites.noSites')"
            @row-click="onRowClick"
            @update:page="goToPage"
            @update:per-page="setItemsPerPage"
        >
            <template #cell-color="{ item }">
                <span class="inline-flex items-center gap-2">
                    <span
                        :style="{ backgroundColor: item.color }"
                        class="inline-block size-5 rounded-full border border-neutral-200"
                    />
                    <span>{{ item.color }}</span>
                </span>
            </template>
            <template #cell-fullAddress="{ item }">
                <span class="line-clamp-2 text-neutral-600">
                    {{ item.fullAddress }}
                </span>
            </template>
        </MalioDataTable>

        <!-- Drawer creation/edition -->
        <SiteDrawer
            v-model="drawerOpen"
            :site="selectedSite"
            @saved="onSiteSaved"
            @delete="onDeleteRequest"
        />

        <!-- Modale de suppression -->
        <SiteDeleteModal
            v-model="deleteModalOpen"
            :site-name="siteToDelete?.name ?? ''"
            :loading="deleting"
            @confirm="handleDelete"
        />
    </div>
</template>

<script setup lang="ts">
import type { Site } from '~/shared/types/sites'

const { t } = useI18n()
const api = useApi()
const auth = useAuthStore()
const { can } = usePermissions()
const canManage = computed(() => can('sites.manage'))

useHead({ title: t('admin.sites.title') })

// Pagination serveur via le composable partage (#73). Aucun OrderFilter
// declare cote API Platform sur Site, donc on s'appuie sur le tri par
// defaut du repository (id ASC). Le composable est neanmoins pret a
// recevoir un `defaultSort` ou des filtres le jour ou l'API les expose.
const {
    items: sites,
    totalItems,
    currentPage,
    itemsPerPage,
    itemsPerPageOptions,
    fetch: loadSites,
    goToPage,
    setItemsPerPage,
} = usePaginatedList<Site>({ url: '/sites' })

const columns = [
    { key: 'name', label: t('admin.sites.table.name') },
    { key: 'city', label: t('admin.sites.table.city') },
    { key: 'postalCode', label: t('admin.sites.table.postalCode') },
    { key: 'color', label: t('admin.sites.table.color') },
    { key: 'fullAddress', label: t('admin.sites.table.fullAddress') },
]

// Transformer les sites en items compatibles MalioDataTable.
// `fullAddress` provient du getter computed cote backend (Site::getFullAddress)
// au format multi-lignes — on l'aplatit en virgules pour l'affichage table.
const siteItems = computed(() =>
    sites.value.map(site => ({
        id: site.id,
        name: site.name,
        city: site.city,
        postalCode: site.postalCode,
        color: site.color,
        fullAddress: site.fullAddress.split('\n').join(', '),
    })),
)

function getSiteById(id: number): Site | undefined {
    return sites.value.find(s => s.id === id)
}

function onRowClick(item: Record<string, unknown>) {
    const site = getSiteById(item.id as number)
    if (site) openEditDrawer(site)
}

const drawerOpen = ref(false)
const selectedSite = ref<Site | null>(null)
const deleteModalOpen = ref(false)
const siteToDelete = ref<Site | null>(null)
const deleting = ref(false)

function openCreateDrawer() {
    selectedSite.value = null
    drawerOpen.value = true
}

function openEditDrawer(site: Site) {
    selectedSite.value = site
    drawerOpen.value = true
}

function onDeleteRequest() {
    if (!selectedSite.value) return
    siteToDelete.value = selectedSite.value
    deleteModalOpen.value = true
}

async function handleDelete() {
    if (!siteToDelete.value) return
    deleting.value = true
    try {
        await api.delete(`/sites/${siteToDelete.value.id}`, {}, {
            toastSuccessMessage: t('admin.sites.toast.deleted'),
        })
        deleteModalOpen.value = false
        siteToDelete.value = null
        drawerOpen.value = false
        await loadSites()
        // Rafraichit auth.user apres suppression d'un site : le backend
        // applique ON DELETE SET NULL sur user.current_site_id, donc
        // auth.user.currentSite peut etre devenu null sans que le front
        // le sache. refreshUser() resynchronise depuis GET /api/me.
        await auth.refreshUser()
    } finally {
        deleting.value = false
    }
}

function onSiteSaved() {
    loadSites()
}

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