<script setup>
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { Head, Link, router, useForm } from '@inertiajs/vue3';
import { ref, computed, watch } from 'vue';

const props = defineProps({
    invoices: Object,
    stats: Object,
    filters: Object,
});

// Search and filters
const search = ref(props.filters.search || '');
const statusFilter = ref(props.filters.status || '');
const paymentMethodFilter = ref(props.filters.payment_method || '');
const fromDate = ref(props.filters.from || '');
const toDate = ref(props.filters.to || '');

// Selection state
const selectedIds = ref([]);
const selectAll = ref(false);

// Modals
const showMarkPaidModal = ref(false);
const showDeleteModal = ref(false);
const showBulkDeleteModal = ref(false);
const selectedInvoice = ref(null);

// Forms
const markPaidForm = useForm({
    payment_method: 'bank_transfer',
    transaction_id: '',
    notes: '',
});

const deleteForm = useForm({
    force: false,
});

// Watch selectAll changes
watch(selectAll, (value) => {
    if (value) {
        selectedIds.value = props.invoices.data.map(inv => inv.id);
    } else {
        selectedIds.value = [];
    }
});

// Computed
const hasSelection = computed(() => selectedIds.value.length > 0);
const selectedCount = computed(() => selectedIds.value.length);
const allSelected = computed(() => {
    return props.invoices.data.length > 0 && 
           selectedIds.value.length === props.invoices.data.length;
});

// Methods
const applyFilters = () => {
    router.get(route('admin.invoices.index'), {
        search: search.value || undefined,
        status: statusFilter.value || undefined,
        payment_method: paymentMethodFilter.value || undefined,
        from: fromDate.value || undefined,
        to: toDate.value || undefined,
    }, { preserveState: true, preserveScroll: true });
};

const clearFilters = () => {
    search.value = '';
    statusFilter.value = '';
    paymentMethodFilter.value = '';
    fromDate.value = '';
    toDate.value = '';
    router.get(route('admin.invoices.index'));
};

const toggleSelection = (id) => {
    const index = selectedIds.value.indexOf(id);
    if (index === -1) {
        selectedIds.value.push(id);
    } else {
        selectedIds.value.splice(index, 1);
    }
    selectAll.value = allSelected.value;
};

const openMarkPaidModal = (invoice) => {
    selectedInvoice.value = invoice;
    markPaidForm.reset();
    showMarkPaidModal.value = true;
};

const submitMarkPaid = () => {
    markPaidForm.post(route('admin.invoices.mark-paid', selectedInvoice.value.id), {
        preserveScroll: true,
        onSuccess: () => {
            showMarkPaidModal.value = false;
            selectedInvoice.value = null;
        },
    });
};

const openDeleteModal = (invoice) => {
    selectedInvoice.value = invoice;
    deleteForm.reset();
    showDeleteModal.value = true;
};

const submitDelete = () => {
    deleteForm.delete(route('admin.invoices.destroy', selectedInvoice.value.id), {
        preserveScroll: true,
        onSuccess: () => {
            showDeleteModal.value = false;
            selectedInvoice.value = null;
        },
    });
};

const openBulkDeleteModal = () => {
    if (selectedIds.value.length === 0) return;
    showBulkDeleteModal.value = true;
};

const submitBulkDelete = () => {
    router.delete(route('admin.invoices.bulk-delete'), {
        data: { ids: selectedIds.value, force: deleteForm.force },
        preserveScroll: true,
        onSuccess: () => {
            showBulkDeleteModal.value = false;
            selectedIds.value = [];
            selectAll.value = false;
        },
    });
};

// Formatters
const formatCurrency = (amount) => {
    return new Intl.NumberFormat('es-DO', { style: 'currency', currency: 'USD' }).format(amount || 0);
};

const formatDate = (date) => {
    if (!date) return '-';
    return new Date(date).toLocaleDateString('es-DO', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
    });
};

const getStatusConfig = (status) => {
    const configs = {
        'paid': { 
            label: 'Pagada', 
            class: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300',
            icon: '✓'
        },
        'pending': { 
            label: 'Pendiente', 
            class: 'bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300',
            icon: '⏳'
        },
        'cancelled': { 
            label: 'Cancelada', 
            class: 'bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-300',
            icon: '✕'
        },
        'overdue': { 
            label: 'Vencida', 
            class: 'bg-orange-100 text-orange-800 dark:bg-orange-900/40 dark:text-orange-300',
            icon: '!'
        },
    };
    return configs[status] || { label: status, class: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300', icon: '?' };
};

const getPaymentMethodLabel = (method) => {
    const methods = {
        'stripe': '💳 Stripe',
        'paypal': '🅿️ PayPal',
        'bank_transfer': '🏦 Transferencia',
        'cash': '💵 Efectivo',
        'wallet': '👛 Billetera',
        'other': '📝 Otro',
    };
    return methods[method] || method || '-';
};

// Debounced search
let searchTimeout;
const debouncedSearch = () => {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(applyFilters, 500);
};
</script>

<template>
    <Head title="Facturas y Pagos" />

    <AdminLayout>
        <template #header>
            <div class="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4">
                <div>
                    <h2 class="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-2">
                        <span class="text-3xl">💰</span>
                        Facturas y Pagos
                    </h2>
                    <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">Gestión completa de pagos y facturación</p>
                </div>
                <div class="flex gap-3">
                    <button 
                        v-if="hasSelection"
                        @click="openBulkDeleteModal"
                        class="inline-flex items-center gap-2 px-4 py-2.5 bg-red-600 text-white rounded-xl text-sm font-medium hover:bg-red-700 transition-all shadow-sm"
                    >
                        <svg class="w-4 h-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>
                        Eliminar ({{ selectedCount }})
                    </button>
                    <a :href="route('admin.invoices.export', { status: statusFilter, from: fromDate, to: toDate })" 
                       class="inline-flex items-center gap-2 px-4 py-2.5 bg-emerald-600 text-white rounded-xl text-sm font-medium hover:bg-emerald-700 transition-all shadow-sm">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                        </svg>
                        Exportar CSV
                    </a>
                </div>
            </div>
        </template>

        <div class="py-6">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 space-y-6">
                
                <!-- Stats Cards -->
                <div class="grid grid-cols-2 md:grid-cols-4 xl:grid-cols-7 gap-4">
                    <div class="bg-white dark:bg-gray-800 rounded-2xl shadow-sm p-5 border border-gray-100 dark:border-gray-700 hover:shadow-md transition-shadow">
                        <div class="flex items-center gap-3">
                            <div class="w-12 h-12 rounded-xl bg-blue-100 dark:bg-blue-900/40 flex items-center justify-center">
                                <span class="text-2xl">📄</span>
                            </div>
                            <div>
                                <div class="text-2xl font-bold text-gray-900 dark:text-white">{{ stats.total_invoices }}</div>
                                <div class="text-xs text-gray-500 dark:text-gray-400 font-medium">Total</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="bg-white dark:bg-gray-800 rounded-2xl shadow-sm p-5 border border-gray-100 dark:border-gray-700 hover:shadow-md transition-shadow">
                        <div class="flex items-center gap-3">
                            <div class="w-12 h-12 rounded-xl bg-emerald-100 dark:bg-emerald-900/40 flex items-center justify-center">
                                <span class="text-2xl">✅</span>
                            </div>
                            <div>
                                <div class="text-2xl font-bold text-emerald-600 dark:text-emerald-400">{{ stats.paid_invoices }}</div>
                                <div class="text-xs text-gray-500 dark:text-gray-400 font-medium">Pagadas</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="bg-white dark:bg-gray-800 rounded-2xl shadow-sm p-5 border border-gray-100 dark:border-gray-700 hover:shadow-md transition-shadow">
                        <div class="flex items-center gap-3">
                            <div class="w-12 h-12 rounded-xl bg-amber-100 dark:bg-amber-900/40 flex items-center justify-center">
                                <span class="text-2xl">⏳</span>
                            </div>
                            <div>
                                <div class="text-2xl font-bold text-amber-600 dark:text-amber-400">{{ stats.pending_invoices }}</div>
                                <div class="text-xs text-gray-500 dark:text-gray-400 font-medium">Pendientes</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="bg-white dark:bg-gray-800 rounded-2xl shadow-sm p-5 border border-gray-100 dark:border-gray-700 hover:shadow-md transition-shadow">
                        <div class="flex items-center gap-3">
                            <div class="w-12 h-12 rounded-xl bg-red-100 dark:bg-red-900/40 flex items-center justify-center">
                                <span class="text-2xl">⚠️</span>
                            </div>
                            <div>
                                <div class="text-2xl font-bold text-red-600 dark:text-red-400">{{ stats.overdue_invoices }}</div>
                                <div class="text-xs text-gray-500 dark:text-gray-400 font-medium">Vencidas</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="bg-gradient-to-br from-emerald-500 to-teal-600 rounded-2xl shadow-sm p-5 text-white">
                        <div class="text-sm font-medium opacity-90">Ingresos Totales</div>
                        <div class="text-2xl font-bold mt-1">{{ formatCurrency(stats.total_revenue) }}</div>
                    </div>
                    
                    <div class="bg-gradient-to-br from-amber-500 to-orange-600 rounded-2xl shadow-sm p-5 text-white">
                        <div class="text-sm font-medium opacity-90">Por Cobrar</div>
                        <div class="text-2xl font-bold mt-1">{{ formatCurrency(stats.pending_revenue) }}</div>
                    </div>
                    
                    <div class="bg-gradient-to-br from-violet-500 to-purple-600 rounded-2xl shadow-sm p-5 text-white">
                        <div class="text-sm font-medium opacity-90">Este Mes</div>
                        <div class="text-2xl font-bold mt-1">{{ formatCurrency(stats.this_month_revenue) }}</div>
                    </div>
                </div>

                <!-- Advanced Filters -->
                <div class="bg-white dark:bg-gray-800 rounded-2xl shadow-sm p-5 border border-gray-100 dark:border-gray-700">
                    <div class="flex items-center gap-2 mb-4">
                        <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" />
                        </svg>
                        <span class="font-medium text-gray-700 dark:text-gray-300">Filtros Avanzados</span>
                    </div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-6 gap-4">
                        <!-- Search -->
                        <div class="lg:col-span-2">
                            <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Buscar</label>
                            <div class="relative">
                                <svg class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                                </svg>
                                <input 
                                    v-model="search" 
                                    type="text" 
                                    placeholder="Factura, nombre o email..."
                                    class="w-full pl-10 pr-4 py-2.5 rounded-xl border-gray-200 dark:border-gray-600 dark:bg-gray-700 dark:text-white text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
                                    @input="debouncedSearch"
                                    @keyup.enter="applyFilters"
                                />
                            </div>
                        </div>
                        
                        <!-- Status -->
                        <div>
                            <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Estado</label>
                            <select v-model="statusFilter" @change="applyFilters" class="w-full py-2.5 rounded-xl border-gray-200 dark:border-gray-600 dark:bg-gray-700 dark:text-white text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500">
                                <option value="">Todos</option>
                                <option value="paid">✅ Pagadas</option>
                                <option value="pending">⏳ Pendientes</option>
                                <option value="cancelled">❌ Canceladas</option>
                            </select>
                        </div>
                        
                        <!-- Payment Method -->
                        <div>
                            <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Método</label>
                            <select v-model="paymentMethodFilter" @change="applyFilters" class="w-full py-2.5 rounded-xl border-gray-200 dark:border-gray-600 dark:bg-gray-700 dark:text-white text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500">
                                <option value="">Todos</option>
                                <option value="stripe">💳 Stripe</option>
                                <option value="paypal">🅿️ PayPal</option>
                                <option value="bank_transfer">🏦 Transferencia</option>
                                <option value="wallet">👛 Billetera</option>
                            </select>
                        </div>
                        
                        <!-- Date From -->
                        <div>
                            <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Desde</label>
                            <input type="date" v-model="fromDate" @change="applyFilters" class="w-full py-2.5 rounded-xl border-gray-200 dark:border-gray-600 dark:bg-gray-700 dark:text-white text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500" />
                        </div>
                        
                        <!-- Date To -->
                        <div>
                            <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Hasta</label>
                            <div class="flex gap-2">
                                <input type="date" v-model="toDate" @change="applyFilters" class="flex-1 py-2.5 rounded-xl border-gray-200 dark:border-gray-600 dark:bg-gray-700 dark:text-white text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500" />
                                <button @click="clearFilters" class="px-3 py-2.5 bg-gray-100 dark:bg-gray-600 text-gray-600 dark:text-gray-300 rounded-xl hover:bg-gray-200 dark:hover:bg-gray-500 transition" title="Limpiar filtros">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                                    </svg>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Invoices Table -->
                <div class="bg-white dark:bg-gray-800 rounded-2xl shadow-sm border border-gray-100 dark:border-gray-700 overflow-hidden">
                    <!-- Selection Bar -->
                    <div v-if="hasSelection" class="px-6 py-3 bg-blue-50 dark:bg-blue-900/30 border-b border-blue-100 dark:border-blue-800 flex items-center justify-between">
                        <span class="text-sm font-medium text-blue-700 dark:text-blue-300">
                            {{ selectedCount }} factura(s) seleccionada(s)
                        </span>
                        <button @click="selectedIds = []; selectAll = false" class="text-sm text-blue-600 dark:text-blue-400 hover:underline">
                            Deseleccionar todo
                        </button>
                    </div>
                    
                    <div class="overflow-x-auto">
                        <table class="w-full">
                            <thead class="bg-gray-50 dark:bg-gray-700/50">
                                <tr>
                                    <th class="px-4 py-4 w-12">
                                        <input 
                                            type="checkbox" 
                                            v-model="selectAll"
                                            class="rounded border-gray-300 dark:border-gray-600 text-blue-600 focus:ring-blue-500"
                                        />
                                    </th>
                                    <th class="px-4 py-4 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Factura</th>
                                    <th class="px-4 py-4 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Cliente</th>
                                    <th class="px-4 py-4 text-left text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider hidden md:table-cell">Plan</th>
                                    <th class="px-4 py-4 text-right text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Total</th>
                                    <th class="px-4 py-4 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Estado</th>
                                    <th class="px-4 py-4 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider hidden lg:table-cell">Método</th>
                                    <th class="px-4 py-4 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider hidden lg:table-cell">Fecha</th>
                                    <th class="px-4 py-4 text-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Acciones</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-100 dark:divide-gray-700">
                                <tr 
                                    v-for="invoice in invoices.data" 
                                    :key="invoice.id" 
                                    :class="[
                                        'hover:bg-gray-50 dark:hover:bg-gray-700/30 transition-colors',
                                        selectedIds.includes(invoice.id) ? 'bg-blue-50/50 dark:bg-blue-900/20' : ''
                                    ]"
                                >
                                    <td class="px-4 py-4">
                                        <input 
                                            type="checkbox" 
                                            :checked="selectedIds.includes(invoice.id)"
                                            @change="toggleSelection(invoice.id)"
                                            class="rounded border-gray-300 dark:border-gray-600 text-blue-600 focus:ring-blue-500"
                                        />
                                    </td>
                                    <td class="px-4 py-4">
                                        <div class="font-mono text-sm font-semibold text-gray-900 dark:text-white">
                                            {{ invoice.invoice_number }}
                                        </div>
                                        <div class="text-xs text-gray-500 dark:text-gray-400">
                                            #{{ invoice.id }}
                                        </div>
                                    </td>
                                    <td class="px-4 py-4">
                                        <div class="flex items-center gap-3">
                                            <div class="w-10 h-10 rounded-full bg-gradient-to-br from-blue-400 to-blue-600 flex items-center justify-center text-white font-bold text-sm shadow-sm">
                                                {{ invoice.user?.name?.charAt(0)?.toUpperCase() || '?' }}
                                            </div>
                                            <div>
                                                <div class="text-sm font-medium text-gray-900 dark:text-white">{{ invoice.user?.name || 'N/A' }}</div>
                                                <div class="text-xs text-gray-500 dark:text-gray-400 truncate max-w-[150px]">{{ invoice.user?.email || 'N/A' }}</div>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="px-4 py-4 hidden md:table-cell">
                                        <span class="inline-flex items-center px-2.5 py-1 rounded-lg bg-gray-100 dark:bg-gray-700 text-xs font-medium text-gray-700 dark:text-gray-300">
                                            {{ invoice.subscription?.plan?.name || 'N/A' }}
                                        </span>
                                    </td>
                                    <td class="px-4 py-4 text-right">
                                        <div class="text-sm font-bold text-gray-900 dark:text-white">{{ formatCurrency(invoice.total) }}</div>
                                        <div v-if="invoice.tax > 0" class="text-xs text-gray-500 dark:text-gray-400">
                                            +{{ formatCurrency(invoice.tax) }} tax
                                        </div>
                                    </td>
                                    <td class="px-4 py-4 text-center">
                                        <span :class="['inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-semibold', getStatusConfig(invoice.status).class]">
                                            <span>{{ getStatusConfig(invoice.status).icon }}</span>
                                            {{ getStatusConfig(invoice.status).label }}
                                        </span>
                                    </td>
                                    <td class="px-4 py-4 text-center hidden lg:table-cell">
                                        <span class="text-sm text-gray-600 dark:text-gray-300">
                                            {{ getPaymentMethodLabel(invoice.payment_method) }}
                                        </span>
                                    </td>
                                    <td class="px-4 py-4 text-center hidden lg:table-cell">
                                        <div class="text-sm text-gray-700 dark:text-gray-300">{{ formatDate(invoice.created_at) }}</div>
                                        <div v-if="invoice.paid_at" class="text-xs text-emerald-600 dark:text-emerald-400">
                                            ✓ {{ formatDate(invoice.paid_at) }}
                                        </div>
                                    </td>
                                    <td class="px-4 py-4">
                                        <div class="flex items-center justify-center gap-1">
                                            <a :href="route('admin.invoices.download', invoice.id)" 
                                               class="p-2 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/30 rounded-lg transition"
                                               title="Descargar PDF"
                                               target="_blank">
                                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                                </svg>
                                            </a>
                                            
                                            <Link :href="route('admin.invoices.show', invoice.id)" 
                                               class="p-2 text-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition"
                                               title="Ver detalles">
                                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                                </svg>
                                            </Link>
                                            
                                            <button v-if="invoice.status === 'pending'"
                                                    @click="openMarkPaidModal(invoice)"
                                                    class="p-2 text-emerald-600 hover:bg-emerald-50 dark:hover:bg-emerald-900/30 rounded-lg transition"
                                                    title="Marcar como pagada">
                                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                                                </svg>
                                            </button>
                                            
                                            <button @click="openDeleteModal(invoice)"
                                                    class="p-2 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/30 rounded-lg transition"
                                                    title="Eliminar factura">
                                                <svg class="w-4 h-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>
                                
                                <tr v-if="!invoices.data.length">
                                    <td colspan="9" class="px-4 py-16 text-center">
                                        <div class="flex flex-col items-center">
                                            <div class="text-6xl mb-4">📭</div>
                                            <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-1">No hay facturas</h3>
                                            <p class="text-gray-500 dark:text-gray-400">No se encontraron facturas con los filtros aplicados.</p>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    <div v-if="invoices.links?.length > 3" class="px-6 py-4 border-t border-gray-100 dark:border-gray-700 flex flex-col sm:flex-row items-center justify-between gap-4">
                        <div class="text-sm text-gray-500 dark:text-gray-400">
                            Mostrando {{ invoices.from || 0 }} a {{ invoices.to || 0 }} de {{ invoices.total || 0 }} resultados
                        </div>
                        <div class="flex flex-wrap justify-center gap-1">
                            <Link 
                                v-for="link in invoices.links" 
                                :key="link.label"
                                :href="link.url"
                                :class="[
                                    'px-4 py-2 rounded-lg text-sm font-medium transition-all',
                                    link.active 
                                        ? 'bg-blue-600 text-white shadow-sm' 
                                        : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600',
                                    !link.url && 'opacity-50 cursor-not-allowed pointer-events-none'
                                ]"
                                v-html="link.label"
                                preserve-scroll
                            />
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Mark as Paid Modal -->
        <Teleport to="body">
            <div v-if="showMarkPaidModal" class="fixed inset-0 z-50 flex items-center justify-center p-4" @click.self="showMarkPaidModal = false">
                <div class="fixed inset-0 bg-gray-900/60 backdrop-blur-sm" @click="showMarkPaidModal = false"></div>
                <div class="relative bg-white dark:bg-gray-800 rounded-2xl shadow-2xl max-w-md w-full p-6">
                    <div class="flex items-center gap-3 mb-6">
                        <div class="w-12 h-12 rounded-full bg-emerald-100 dark:bg-emerald-900/40 flex items-center justify-center">
                            <span class="text-2xl">✅</span>
                        </div>
                        <div>
                            <h3 class="text-lg font-bold text-gray-900 dark:text-white">Confirmar Pago</h3>
                            <p class="text-sm text-gray-500 dark:text-gray-400">{{ selectedInvoice?.invoice_number }}</p>
                        </div>
                    </div>

                    <div class="bg-gray-50 dark:bg-gray-700/50 rounded-xl p-4 mb-6">
                        <div class="flex justify-between items-center">
                            <span class="text-gray-600 dark:text-gray-400">Monto:</span>
                            <span class="text-xl font-bold text-gray-900 dark:text-white">{{ formatCurrency(selectedInvoice?.total) }}</span>
                        </div>
                    </div>

                    <form @submit.prevent="submitMarkPaid" class="space-y-4">
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">Método de Pago *</label>
                            <select v-model="markPaidForm.payment_method" class="w-full rounded-xl border-gray-200 dark:border-gray-600 dark:bg-gray-700 dark:text-white">
                                <option value="stripe">💳 Stripe</option>
                                <option value="paypal">🅿️ PayPal</option>
                                <option value="bank_transfer">🏦 Transferencia</option>
                                <option value="cash">💵 Efectivo</option>
                                <option value="wallet">👛 Billetera</option>
                                <option value="other">📝 Otro</option>
                            </select>
                        </div>

                        <div>
                            <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">ID Transacción</label>
                            <input type="text" v-model="markPaidForm.transaction_id" class="w-full rounded-xl border-gray-200 dark:border-gray-600 dark:bg-gray-700 dark:text-white" placeholder="TXN_123456789" />
                        </div>

                        <div>
                            <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">Notas</label>
                            <textarea v-model="markPaidForm.notes" rows="2" class="w-full rounded-xl border-gray-200 dark:border-gray-600 dark:bg-gray-700 dark:text-white" placeholder="Notas adicionales..."></textarea>
                        </div>

                        <div class="flex justify-end gap-3 pt-4">
                            <button type="button" @click="showMarkPaidModal = false" class="px-5 py-2.5 text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-xl font-medium transition">
                                Cancelar
                            </button>
                            <button type="submit" :disabled="markPaidForm.processing" class="px-6 py-2.5 bg-emerald-600 text-white rounded-xl font-medium hover:bg-emerald-700 disabled:opacity-50 transition">
                                {{ markPaidForm.processing ? 'Procesando...' : 'Confirmar Pago' }}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </Teleport>

        <!-- Delete Single Modal -->
        <Teleport to="body">
            <div v-if="showDeleteModal" class="fixed inset-0 z-50 flex items-center justify-center p-4" @click.self="showDeleteModal = false">
                <div class="fixed inset-0 bg-gray-900/60 backdrop-blur-sm" @click="showDeleteModal = false"></div>
                <div class="relative bg-white dark:bg-gray-800 rounded-2xl shadow-2xl max-w-md w-full p-6">
                    <div class="flex items-center gap-3 mb-6">
                        <div class="w-12 h-12 rounded-full bg-red-100 dark:bg-red-900/40 flex items-center justify-center">
                            <span class="text-2xl">🗑️</span>
                        </div>
                        <div>
                            <h3 class="text-lg font-bold text-gray-900 dark:text-white">Eliminar Factura</h3>
                            <p class="text-sm text-gray-500 dark:text-gray-400">{{ selectedInvoice?.invoice_number }}</p>
                        </div>
                    </div>

                    <p class="text-gray-600 dark:text-gray-300 mb-4">
                        ¿Estás seguro de que deseas eliminar esta factura? Esta acción no se puede deshacer.
                    </p>

                    <div v-if="selectedInvoice?.status === 'paid'" class="bg-amber-50 dark:bg-amber-900/30 border border-amber-200 dark:border-amber-700 rounded-xl p-4 mb-4">
                        <p class="text-sm font-medium text-amber-800 dark:text-amber-300 mb-2">⚠️ Esta factura está pagada</p>
                        <label class="flex items-center gap-2">
                            <input type="checkbox" v-model="deleteForm.force" class="rounded border-amber-300 text-amber-600 focus:ring-amber-500" />
                            <span class="text-sm text-amber-700 dark:text-amber-300">Confirmo la eliminación</span>
                        </label>
                    </div>

                    <div class="flex justify-end gap-3 pt-4">
                        <button @click="showDeleteModal = false" class="px-5 py-2.5 text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-xl font-medium transition">
                            Cancelar
                        </button>
                        <button 
                            @click="submitDelete" 
                            :disabled="deleteForm.processing || (selectedInvoice?.status === 'paid' && !deleteForm.force)"
                            class="px-6 py-2.5 bg-red-600 text-white rounded-xl font-medium hover:bg-red-700 disabled:opacity-50 transition"
                        >
                            {{ deleteForm.processing ? 'Eliminando...' : 'Eliminar' }}
                        </button>
                    </div>
                </div>
            </div>
        </Teleport>

        <!-- Bulk Delete Modal -->
        <Teleport to="body">
            <div v-if="showBulkDeleteModal" class="fixed inset-0 z-50 flex items-center justify-center p-4" @click.self="showBulkDeleteModal = false">
                <div class="fixed inset-0 bg-gray-900/60 backdrop-blur-sm" @click="showBulkDeleteModal = false"></div>
                <div class="relative bg-white dark:bg-gray-800 rounded-2xl shadow-2xl max-w-md w-full p-6">
                    <div class="flex items-center gap-3 mb-6">
                        <div class="w-12 h-12 rounded-full bg-red-100 dark:bg-red-900/40 flex items-center justify-center">
                            <span class="text-2xl">⚠️</span>
                        </div>
                        <div>
                            <h3 class="text-lg font-bold text-gray-900 dark:text-white">Eliminar {{ selectedCount }} Facturas</h3>
                            <p class="text-sm text-gray-500 dark:text-gray-400">Eliminación masiva</p>
                        </div>
                    </div>

                    <div class="bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-700 rounded-xl p-4 mb-4">
                        <p class="text-sm text-red-700 dark:text-red-300">
                            Esta acción eliminará <strong>{{ selectedCount }}</strong> factura(s) permanentemente.
                        </p>
                    </div>

                    <label class="flex items-center gap-2 mb-6">
                        <input type="checkbox" v-model="deleteForm.force" class="rounded border-gray-300 text-red-600 focus:ring-red-500" />
                        <span class="text-sm text-gray-700 dark:text-gray-300">Incluir facturas pagadas</span>
                    </label>

                    <div class="flex justify-end gap-3 pt-4">
                        <button @click="showBulkDeleteModal = false" class="px-5 py-2.5 text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-xl font-medium transition">
                            Cancelar
                        </button>
                        <button @click="submitBulkDelete" class="px-6 py-2.5 bg-red-600 text-white rounded-xl font-medium hover:bg-red-700 transition">
                            Eliminar {{ selectedCount }} Facturas
                        </button>
                    </div>
                </div>
            </div>
        </Teleport>
    </AdminLayout>
</template>
