<script setup>
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue'
import Pagination from '@/Components/Pagination.vue'
import { Head, Link, router } from '@inertiajs/vue3'
import { ref, reactive } from 'vue'

const props = defineProps({
    licences:     Object,
    communes:     Array,
    fournisseurs: Array,
    filters:      Object,
})

const filters = reactive({
    search: props.filters.search || '',
    commune_id: props.filters.commune_id || '',
    fournisseur_id: props.filters.fournisseur_id || '',
})

function applyFilters() {
    router.get(route('licences.index'), filters, { preserveState: true, replace: true })
}

function formatDate(d) {
    if (!d) return '—'
    return new Intl.DateTimeFormat('fr-FR').format(new Date(d))
}

const statutColors = {
    active: 'bg-green-100 text-green-800',
    'expirée': 'bg-red-100 text-red-800',
    'résiliée': 'bg-gray-100 text-gray-800',
}

function getUsageColor(rate) {
    if (rate >= 90) return 'bg-red-500'
    if (rate >= 75) return 'bg-orange-500'
    return 'bg-blue-500'
}
</script>

<template>
    <Head title="Gestion des Licences" />
    <AuthenticatedLayout>
        <template #header>
            <div class="flex items-center justify-between">
                <h1 class="text-xl font-semibold text-gray-900">Licences & Abonnements</h1>
                <Link :href="route('licences.create')"
                    class="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 transition-colors">
                    + Nouvelle licence
                </Link>
            </div>
        </template>

        <div class="space-y-4">
            <!-- Filtres -->
            <div class="rounded-xl bg-white p-4 shadow-sm border border-gray-100">
                <div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
                    <input v-model="filters.search" @input="applyFilters" type="text" placeholder="Recherche produit..."
                        class="rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-indigo-500 focus:outline-none" />

                    <select v-model="filters.commune_id" @change="applyFilters"
                        class="rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-indigo-500 focus:outline-none">
                        <option value="">Toutes les communes</option>
                        <option v-for="c in communes" :key="c.id" :value="c.id">{{ c.nom }}</option>
                    </select>

                    <select v-model="filters.fournisseur_id" @change="applyFilters"
                        class="rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-indigo-500 focus:outline-none">
                        <option value="">Tous les fournisseurs</option>
                        <option v-for="f in fournisseurs" :key="f.id" :value="f.id">{{ f.nom }}</option>
                    </select>
                </div>
            </div>

            <!-- Table -->
            <div class="rounded-xl bg-white shadow-sm border border-gray-100 overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-100 text-sm">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Produit / Logiciel</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Commune</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Fournisseur / Contrat</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Utilisation Sièges</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Expiration</th>
                                <th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-50 text-gray-600">
                            <tr v-for="lic in licences.data" :key="lic.id" class="hover:bg-gray-50 transition-colors">
                                <td class="px-4 py-3">
                                    <div class="font-medium text-gray-900">{{ lic.nom }}</div>
                                    <div class="text-xs text-xs">{{ lic.type_licence }}</div>
                                </td>
                                <td class="px-4 py-3">{{ lic.commune?.nom ?? '—' }}</td>
                                <td class="px-4 py-3">
                                    <div>{{ lic.fournisseur?.nom }}</div>
                                    <div class="text-xs text-indigo-500" v-if="lic.contrat">
                                        {{ lic.contrat.titre }}
                                    </div>
                                </td>
                                <td class="px-4 py-3">
                                    <div class="flex items-center gap-2">
                                        <div class="w-24 h-2 bg-gray-100 rounded-full overflow-hidden">
                                            <div :class="['h-full transition-all', getUsageColor((lic.nombre_sieges_utilises / lic.nombre_sieges_total) * 100)]"
                                                :style="{ width: Math.min((lic.nombre_sieges_utilises / lic.nombre_sieges_total) * 100, 100) + '%' }">
                                            </div>
                                        </div>
                                        <span class="text-xs font-bold">{{ lic.nombre_sieges_utilises }} / {{ lic.nombre_sieges_total }}</span>
                                    </div>
                                </td>
                                <td class="px-4 py-3">
                                    <span :class="['px-2 py-0.5 rounded-full text-xs font-medium', statutColors[lic.statut]]">
                                        {{ lic.statut }}
                                    </span>
                                    <div class="mt-1 text-xs" v-if="lic.date_expiration">
                                        Éxpire le {{ formatDate(lic.date_expiration) }}
                                    </div>
                                </td>
                                <td class="px-4 py-3 text-center">
                                    <div class="flex items-center justify-center gap-2">
                                        <Link :href="route('licences.edit', lic.id)"
                                            class="p-1 text-gray-400 hover:text-blue-600 transition-colors">
                                            <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                            </svg>
                                        </Link>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="px-4 py-3 border-t border-gray-100">
                    <Pagination :links="licences.links" />
                </div>
            </div>
        </div>
    </AuthenticatedLayout>
</template>
