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

const props = defineProps({
    domaines: Object,
    filters:  Object,
})

const page = usePage()
const filters = reactive({ ...props.filters })
const deleteTarget = ref(null)

const canManage = computed(() => {
    return page.props.auth.user?.roles?.some(r => r.name === 'admin') ||
           page.props.auth.user?.service?.nom === 'Infrastructure';
})

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

function resetFilters() {
    filters.search = ''
    applyFilters()
}

function confirmDelete(dom) {
    deleteTarget.value = dom
}

const deleteForm = useForm({})
function doDelete() {
    deleteForm.delete(route('domaines.destroy', deleteTarget.value.id), {
        onSuccess: () => deleteTarget.value = null,
    })
}

const syncForm = useForm({})
function doSync(domId) {
    syncForm.post(route('domaines.sync-whois', domId), {
        preserveScroll: true,
    })
}

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

<template>
    <Head title="Noms de Domaine" />
    <AuthenticatedLayout>
        <template #header>
            <div class="flex items-center justify-between">
                <h1 class="text-xl font-semibold text-gray-900">Noms de Domaine</h1>
                <Link v-if="canManage" :href="route('domaines.create')"
                    class="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 transition-colors">
                    + Nouveau domaine
                </Link>
            </div>
        </template>

        <div class="space-y-4">
            <!-- Filtres -->
            <div class="rounded-xl bg-white p-4 shadow-sm border border-gray-100 flex items-center justify-between">
                <div class="w-full max-w-sm">
                    <input v-model="filters.search" @input="applyFilters" type="text" placeholder="Recherche (nom, prestataire)..."
                        class="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-indigo-500 focus:outline-none" />
                </div>
                <button v-if="filters.search" @click="resetFilters"
                    class="ml-3 rounded-lg border border-gray-300 px-3 py-2 text-sm text-gray-600 hover:bg-gray-50 transition-colors">
                    Réinitialiser
                </button>
            </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">Nom de domaine</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Hébergeur</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Prestataire</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Date d'échéance</th>
                                <th v-if="canManage" 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">
                            <tr v-for="dom in domaines.data" :key="dom.id"
                                :class="['hover:bg-gray-50 transition-colors', dom.est_en_retard ? 'bg-red-50/50' : (dom.est_proche_echeance ? 'bg-orange-50/50' : '')]">
                                <td class="px-4 py-3 font-medium text-gray-900 border-l-4" :class="dom.est_en_retard ? 'border-red-400' : (dom.est_proche_echeance ? 'border-orange-400' : 'border-transparent')">
                                    <a :href="`https://${dom.nom}`" target="_blank" class="text-indigo-600 hover:underline inline-flex items-center gap-1">
                                        {{ dom.nom }}
                                    </a>
                                </td>
                                <td class="px-4 py-3 whitespace-nowrap text-gray-600">{{ dom.hebergeur || '—' }}</td>
                                <td class="px-4 py-3 text-gray-600">{{ dom.prestataire || '—' }}</td>
                                <td class="px-4 py-3 whitespace-nowrap" :class="[dom.est_en_retard ? 'text-red-600 font-bold' : (dom.est_proche_echeance ? 'text-orange-600 font-bold' : 'text-gray-600')]">
                                    <div class="flex items-center gap-2">
                                        {{ formatDate(dom.date_echeance) }}
                                        <span v-if="dom.est_en_retard" class="text-xs" title="Échéance dépassée">⚠️</span>
                                        <span v-else-if="dom.est_proche_echeance" class="text-xs" title="Proche de l'échéance">⏳</span>
                                        
                                        <button v-if="canManage" @click="doSync(dom.id)" title="Synchroniser via WHOIS"
                                            class="p-1 text-gray-400 hover:text-indigo-600 transition-colors disabled:opacity-50">
                                            <svg class="h-4 w-4" :class="{'animate-spin text-indigo-600': syncForm.processing && dom.id == syncForm.domId}" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                                            </svg>
                                        </button>
                                    </div>
                                </td>
                                <td v-if="canManage" class="px-4 py-3 text-center">
                                    <div class="flex items-center justify-center gap-2">
                                        <Link :href="route('domaines.edit', dom.id)"
                                            class="text-gray-400 hover:text-blue-600 transition-colors" title="Modifier">
                                            <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>
                                        <button @click="confirmDelete(dom)"
                                            class="text-gray-400 hover:text-red-600 transition-colors" title="Supprimer">
                                            <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                            </svg>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <div v-if="!domaines.data.length" class="py-12 text-center text-gray-400">
                    Aucun nom de domaine trouvé.
                </div>

                <div class="border-t border-gray-100 px-4 py-3">
                    <Pagination :links="domaines.links" :meta="domaines.meta" />
                </div>
            </div>
        </div>

        <ConfirmModal :show="!!deleteTarget"
            title="Supprimer le domaine"
            :message="`Supprimer définitivement le nom de domaine '${deleteTarget?.nom}' ?`"
            :processing="deleteForm.processing"
            @confirm="doDelete"
            @cancel="deleteTarget = null" />
    </AuthenticatedLayout>
</template>
