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

        <!-- Table des sites -->
        <MalioDataTable
            :columns="columns"
            :items="siteItems"
            :total-items="sites.length"
            :row-clickable="canManage"
            :empty-message="t('admin.sites.noSites')"
            @row-click="onRowClick"
        >
            <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 class="font-mono text-xs">{{ item.color }}</span>
                </span>
            </template>
            <template #cell-fullAddress="{ item }">
                <span class="line-clamp-2 text-xs 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') })

const sites = ref<Site[]>([])
const loading = ref(false)

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)

async function loadSites() {
    loading.value = true
    try {
        const data = await api.get<{ member: Site[] }>(
            '/sites',
            { itemsPerPage: 999 },
            { toast: false },
        )
        sites.value = data.member
    } catch {
        // Reset sur echec pour ne pas afficher de donnees stale (ancienne
        // requete reussie avant une perte reseau ou 403).
        sites.value = []
    } finally {
        loading.value = 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>
