<x-app-layout>
    <div class="max-w-[1600px] mx-auto p-4 md:p-6 antialiased">
        <!-- Header Section -->
        <div class="mb-6 space-y-4">
            <div
                class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 bg-white dark:bg-[#1a1a2e] p-5 rounded-3xl border border-slate-200 dark:border-white/5 shadow-sm">
                <div>
                    <h1 class="text-2xl md:text-3xl font-black tracking-tight dark:text-white">
                        <span class="bg-gradient-to-r from-violet-600 to-indigo-600 bg-clip-text text-transparent">
                            Validasi Mahasiswa
                        </span>
                    </h1>
                    <p class="text-slate-500 dark:text-slate-400 text-sm mt-1 flex items-center">
                        <i data-lucide="user-check" class="w-4 h-4 mr-2"></i>
                        Daftar mahasiswa yang menunggu validasi data
                    </p>
                </div>

                <div class="flex items-center gap-4">
                    <button onclick="window.print()"
                        class="px-4 py-2.5 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-xl text-sm font-medium text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-gray-700 transition-all flex items-center gap-2 shadow-sm">
                        <i data-lucide="printer" class="w-4 h-4"></i>
                        <span class="hidden sm:inline">Print</span>
                    </button>
                </div>
            </div>

            <!-- Search Form -->
            <div class="bg-white dark:bg-[#1a1a2e] p-4 rounded-2xl border border-slate-200 dark:border-white/5 shadow-sm">
                <form method="GET" action="{{ route('validasi.mahasiswa.index') }}" class="relative">
                    <div class="relative">
                        <i data-lucide="search" class="absolute left-4 top-1/2 transform -translate-y-1/2 w-4 h-4 text-slate-400"></i>
                        <input type="text" name="search" value="{{ request('search') }}"
                            placeholder="Cari NIM, nama, atau prodi..."
                            class="w-full pl-12 pr-10 py-2.5 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-xl text-gray-700 dark:text-gray-300 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-violet-500 focus:border-transparent transition-all">
                        @if (request('search'))
                            <a href="{{ route('validasi.mahasiswa.index') }}"
                                class="absolute right-3 top-1/2 transform -translate-y-1/2 text-slate-400 hover:text-slate-600">
                                <i data-lucide="x" class="w-4 h-4"></i>
                            </a>
                        @endif
                    </div>
                </form>
            </div>
        </div>

        <!-- Main Card -->
        <div class="bg-white dark:bg-[#1a1a2e] rounded-3xl border border-slate-200 dark:border-white/5 shadow-xl overflow-hidden">

            <!-- Card Header with Stats -->
            <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 p-6 pb-4 border-b border-slate-100 dark:border-white/5">
                <div class="flex items-center gap-4">
                    <div class="w-12 h-12 rounded-2xl bg-gradient-to-br from-violet-500/10 to-indigo-600/10 text-violet-500 flex items-center justify-center">
                        <i data-lucide="users" class="w-6 h-6"></i>
                    </div>
                    <div>
                        <h3 class="text-xl font-bold text-gray-900 dark:text-white">Data Menunggu Validasi</h3>
                        <p class="text-sm text-slate-500 dark:text-slate-400">
                            Total: {{ $data->count() }} Mahasiswa
                        </p>
                    </div>
                </div>
            </div>

            @if ($data->count() > 0)
                <!-- Bulk Actions -->
                <form id="bulkSetujuiForm" method="POST" action="{{ route('validasi.mahasiswa.bulk.setujui') }}">
                    @csrf

                    <div class="m-4 p-4 bg-gradient-to-r from-slate-50 to-gray-50 dark:from-gray-800/50 dark:to-gray-900/50 border border-slate-200 dark:border-gray-700 rounded-2xl">
                        <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                            <div class="flex items-center gap-3">
                                <div class="flex items-center">
                                    <input type="checkbox" id="checkAll" class="w-4 h-4 text-violet-600 bg-gray-100 border-gray-300 rounded focus:ring-violet-500 focus:ring-2">
                                    <label for="checkAll" class="ml-2 text-sm font-medium text-gray-900 dark:text-gray-300">
                                        Pilih Semua
                                    </label>
                                </div>
                                <span class="text-sm text-slate-500 dark:text-slate-400">
                                    (<span id="selectedCount">0</span> terpilih)
                                </span>
                            </div>

                            <div class="flex gap-3">
                                <button type="button" id="bulkSetujuiBtn" disabled
                                    class="px-4 py-2.5 bg-gradient-to-r from-emerald-600 to-green-700 text-white rounded-xl text-sm font-medium hover:shadow-lg hover:shadow-emerald-500/25 transition-all flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed">
                                    <i data-lucide="check" class="w-4 h-4"></i>
                                    Setujui Terpilih
                                </button>

                                <button type="button" id="bulkTolakBtn" disabled
                                    class="px-4 py-2.5 bg-gradient-to-r from-red-600 to-rose-700 text-white rounded-xl text-sm font-medium hover:shadow-lg hover:shadow-red-500/25 transition-all flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed">
                                    <i data-lucide="x" class="w-4 h-4"></i>
                                    Tolak Terpilih
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Table - Responsive dengan overflow-x-auto di wrapper mobile -->
                    <div class="overflow-x-auto">
                        <table class="w-full min-w-[640px]">
                            <thead>
                                <tr class="bg-gradient-to-r from-slate-50 to-gray-50 dark:from-gray-800 dark:to-gray-900 border-b border-slate-200 dark:border-gray-700">
                                    <th class="py-4 px-4 text-left w-12">
                                        <input type="checkbox" id="checkAllHeader" class="w-4 h-4 text-violet-600 bg-gray-100 border-gray-300 rounded focus:ring-violet-500 focus:ring-2">
                                    </th>
                                    <th class="py-4 px-4 text-left text-sm font-semibold text-gray-900 dark:text-white">NIM</th>
                                    <th class="py-4 px-4 text-left text-sm font-semibold text-gray-900 dark:text-white">Nama</th>
                                    <th class="py-4 px-4 text-left text-sm font-semibold text-gray-900 dark:text-white">Prodi</th>
                                    <th class="py-4 px-4 text-left text-sm font-semibold text-gray-900 dark:text-white">Kampus</th>
                                    <th class="py-4 px-4 text-left text-sm font-semibold text-gray-900 dark:text-white">Angkatan</th>
                                    <th class="py-4 px-4 text-left text-sm font-semibold text-gray-900 dark:text-white">Aksi</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-200 dark:divide-gray-700">
                                @foreach ($data as $mhs)
                                    <tr class="hover:bg-slate-50 dark:hover:bg-gray-800/50 transition-colors">
                                        <td class="py-4 px-4">
                                            <input type="checkbox" name="ids[]" value="{{ $mhs->id }}" class="row-check w-4 h-4 text-violet-600 bg-gray-100 border-gray-300 rounded focus:ring-violet-500 focus:ring-2">
                                        </td>
                                        <td class="py-4 px-4 font-mono text-sm font-medium text-gray-900 dark:text-white">
                                            {{ $mhs->nim }}
                                        </td>
                                        <td class="py-4 px-4">
                                            <div class="font-medium text-gray-900 dark:text-white">
                                                {{ $mhs->nama }}
                                            </div>
                                            @if ($mhs->email)
                                                <div class="text-sm text-slate-500 dark:text-slate-400 mt-1">
                                                    {{ $mhs->email }}
                                                </div>
                                            @endif
                                        </td>
                                        <td class="py-4 px-4">{{ $mhs->prodi->nama ?? '-' }}</td>
                                        <td class="py-4 px-4">{{ $mhs->kampus->nama ?? '-' }}</td>
                                        <td class="py-4 px-4">
                                            <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200">
                                                {{ $mhs->angkatan }}
                                            </span>
                                        </td>
                                        <td class="py-4 px-4">
                                            <div class="flex items-center gap-2">
                                                <button type="button" data-id="{{ $mhs->id }}" data-nama="{{ $mhs->nama }}"
                                                    class="individual-setujui-btn px-3 py-1.5 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 hover:bg-emerald-500/20 rounded-lg text-sm font-medium transition-all flex items-center gap-2">
                                                    <i data-lucide="check" class="w-4 h-4"></i>
                                                    Setujui
                                                </button>

                                                <button type="button" data-id="{{ $mhs->id }}" data-nama="{{ $mhs->nama }}"
                                                    class="individual-tolak-btn px-3 py-1.5 bg-red-500/10 text-red-600 dark:text-red-400 hover:bg-red-500/20 rounded-lg text-sm font-medium transition-all flex items-center gap-2">
                                                    <i data-lucide="x" class="w-4 h-4"></i>
                                                    Tolak
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </form>
            @else
                <!-- Empty State -->
                <div class="text-center py-12">
                    <div class="w-20 h-20 mx-auto mb-6 rounded-2xl bg-gradient-to-br from-slate-100 to-gray-100 dark:from-gray-800 dark:to-gray-900 flex items-center justify-center">
                        <i data-lucide="users" class="w-10 h-10 text-slate-400"></i>
                    </div>
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-2">
                        @if (request('search'))
                            Tidak ditemukan mahasiswa dengan kata kunci "{{ request('search') }}"
                        @else
                            Belum ada mahasiswa menunggu validasi
                        @endif
                    </h3>
                    <p class="text-slate-500 dark:text-slate-400 mb-6">
                        Semua data mahasiswa sudah tervalidasi
                    </p>
                    @if (request('search'))
                        <a href="{{ route('validasi.mahasiswa.index') }}"
                            class="inline-flex items-center gap-2 px-4 py-2.5 bg-gradient-to-r from-violet-600 to-indigo-700 text-white rounded-xl text-sm font-medium hover:shadow-lg hover:shadow-violet-500/25 transition-all">
                            <i data-lucide="refresh-cw" class="w-4 h-4"></i>
                            Tampilkan Semua
                        </a>
                    @endif
                </div>
            @endif
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            lucide.createIcons();

            const checkAll = document.getElementById('checkAll');
            const checkAllHeader = document.getElementById('checkAllHeader');
            const rowChecks = document.querySelectorAll('.row-check');
            const bulkSetujuiBtn = document.getElementById('bulkSetujuiBtn');
            const bulkTolakBtn = document.getElementById('bulkTolakBtn');
            const selectedCount = document.getElementById('selectedCount');
            const bulkSetujuiForm = document.getElementById('bulkSetujuiForm');

            // Check dark mode
            const isDarkMode = document.documentElement.classList.contains('dark');

            // SweetAlert configuration dengan tema yang sesuai
            const SwalModal = Swal.mixin({
                background: isDarkMode ? '#1a1a2e' : '#ffffff',
                color: isDarkMode ? '#e5e7eb' : '#374151',
                confirmButtonColor: '#8b5cf6',
                cancelButtonColor: '#ef4444',
                backdrop: isDarkMode ? 'rgba(0, 0, 0, 0.7)' : 'rgba(0, 0, 0, 0.5)',
                customClass: {
                    popup: 'rounded-2xl shadow-2xl',
                    title: 'font-bold text-xl',
                    htmlContainer: 'text-sm',
                    confirmButton: 'px-5 py-2.5 rounded-xl font-medium transition-all hover:shadow-lg',
                    cancelButton: 'px-5 py-2.5 rounded-xl font-medium transition-all hover:shadow-lg'
                }
            });

            // ========== SESSION NOTIFICATIONS ==========
            @if (session('success'))
                SwalModal.fire({
                    icon: 'success',
                    title: 'Berhasil!',
                    text: "{{ session('success') }}",
                    showConfirmButton: true,
                    confirmButtonText: 'Mengerti',
                    timer: 3000,
                    timerProgressBar: true
                });
            @endif

            @if (session('error'))
                SwalModal.fire({
                    icon: 'error',
                    title: 'Gagal!',
                    text: "{{ session('error') }}",
                    showConfirmButton: true,
                    confirmButtonText: 'Mengerti'
                });
            @endif

            // ========== UPDATE SELECTION ==========
            function updateSelection() {
                if (!selectedCount || !bulkSetujuiBtn || !bulkTolakBtn) return;

                const selected = document.querySelectorAll('.row-check:checked');
                const count = selected.length;

                selectedCount.textContent = count;
                bulkSetujuiBtn.disabled = count === 0;
                bulkTolakBtn.disabled = count === 0;

                // Update button text with count
                if (count > 0) {
                    bulkSetujuiBtn.innerHTML = `<i data-lucide="check" class="w-4 h-4"></i> Setujui (${count})`;
                    bulkTolakBtn.innerHTML = `<i data-lucide="x" class="w-4 h-4"></i> Tolak (${count})`;
                    lucide.createIcons();
                } else {
                    bulkSetujuiBtn.innerHTML = `<i data-lucide="check" class="w-4 h-4"></i> Setujui Terpilih`;
                    bulkTolakBtn.innerHTML = `<i data-lucide="x" class="w-4 h-4"></i> Tolak Terpilih`;
                    lucide.createIcons();
                }

                const allChecked = count === rowChecks.length;
                const someChecked = count > 0 && !allChecked;

                if (checkAll) {
                    checkAll.checked = allChecked;
                    checkAll.indeterminate = someChecked;
                }
                if (checkAllHeader) {
                    checkAllHeader.checked = allChecked;
                    checkAllHeader.indeterminate = someChecked;
                }
            }

            // ========== SETUP SELECT ALL ==========
            function setupSelectAll(checkbox, targetCheckboxes) {
                if (checkbox) {
                    checkbox.addEventListener('change', function() {
                        targetCheckboxes.forEach(ch => {
                            ch.checked = this.checked;
                        });
                        updateSelection();
                    });
                }
            }

            setupSelectAll(checkAll, rowChecks);
            setupSelectAll(checkAllHeader, rowChecks);

            rowChecks.forEach(checkbox => {
                checkbox.addEventListener('change', updateSelection);
            });

            if (rowChecks.length > 0) updateSelection();

            // ========== SHOW BULK ACTION ALERT ==========
            function showBulkActionAlert(action, count) {
                const actionText = action === 'setujui' ? 'menyetujui' : 'menolak';
                const actionColor = action === 'setujui' ? '#10b981' : '#ef4444';
                const titleText = action === 'setujui' ? 'Setujui Data Massal?' : 'Tolak Data Massal?';

                SwalModal.fire({
                    title: titleText,
                    html: `Anda akan <strong>${actionText} ${count} mahasiswa</strong><br><br>
                           <span class="text-amber-500 font-semibold">⚠️ Pastikan Anda sudah mengecek semua data dengan teliti!</span>`,
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: `Ya, ${action === 'setujui' ? 'Setujui' : 'Tolak'} ${count} Data`,
                    cancelButtonText: 'Periksa Kembali',
                    confirmButtonColor: actionColor,
                    cancelButtonColor: '#64748b',
                    reverseButtons: true,
                    width: '500px'
                }).then((result) => {
                    if (result.isConfirmed) {
                        executeBulkAction(action);
                    }
                });
            }

            // ========== EXECUTE BULK ACTION ==========
            function executeBulkAction(action) {
                const selected = document.querySelectorAll('.row-check:checked');
                const ids = Array.from(selected).map(cb => cb.value);

                if (ids.length === 0) return;

                const form = document.createElement('form');
                form.method = 'POST';
                if (action === 'setujui') {
                    form.action = '{{ route('validasi.mahasiswa.bulk.setujui') }}';
                } else {
                    form.action = '{{ route('validasi.mahasiswa.bulk.tolak') }}';
                }

                const csrfToken = document.createElement('input');
                csrfToken.type = 'hidden';
                csrfToken.name = '_token';
                csrfToken.value = '{{ csrf_token() }}';
                form.appendChild(csrfToken);

                ids.forEach(id => {
                    const input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = 'ids[]';
                    input.value = id;
                    form.appendChild(input);
                });

                // Show loading
                if (action === 'setujui') {
                    bulkSetujuiBtn.innerHTML = '<i data-lucide="loader-2" class="w-4 h-4 animate-spin mr-2"></i> Memproses...';
                    bulkSetujuiBtn.disabled = true;
                } else {
                    bulkTolakBtn.innerHTML = '<i data-lucide="loader-2" class="w-4 h-4 animate-spin mr-2"></i> Memproses...';
                    bulkTolakBtn.disabled = true;
                }
                lucide.createIcons();

                document.body.appendChild(form);
                form.submit();
            }

            // ========== BULK SETUJUI BUTTON ==========
            bulkSetujuiBtn?.addEventListener('click', function() {
                const selected = document.querySelectorAll('.row-check:checked');
                const count = selected.length;

                if (count === 0) {
                    SwalModal.fire({
                        title: 'Peringatan!',
                        text: 'Pilih minimal satu mahasiswa!',
                        icon: 'warning',
                        confirmButtonText: 'Mengerti',
                        confirmButtonColor: '#f59e0b'
                    });
                    return;
                }

                showBulkActionAlert('setujui', count);
            });

            // ========== BULK TOLAK BUTTON ==========
            bulkTolakBtn?.addEventListener('click', function() {
                const selected = document.querySelectorAll('.row-check:checked');
                const count = selected.length;

                if (count === 0) {
                    SwalModal.fire({
                        title: 'Peringatan!',
                        text: 'Pilih minimal satu mahasiswa!',
                        icon: 'warning',
                        confirmButtonText: 'Mengerti',
                        confirmButtonColor: '#f59e0b'
                    });
                    return;
                }

                showBulkActionAlert('tolak', count);
            });

            // ========== SUBMIT INDIVIDUAL ACTION ==========
            function submitIndividualAction(action, id, nama) {
                SwalModal.fire({
                    title: action === 'setujui' ? 'Setujui Mahasiswa?' : 'Tolak Mahasiswa?',
                    html: `Anda akan ${action === 'setujui' ? 'menyetujui' : 'menolak'} <strong>${nama}</strong>`,
                    icon: action === 'setujui' ? 'question' : 'warning',
                    showCancelButton: true,
                    confirmButtonText: action === 'setujui' ? 'Ya, Setujui!' : 'Ya, Tolak!',
                    cancelButtonText: 'Batal',
                    confirmButtonColor: action === 'setujui' ? '#10b981' : '#ef4444',
                    cancelButtonColor: '#64748b',
                    reverseButtons: true
                }).then(result => {
                    if (result.isConfirmed) {
                        const form = document.createElement('form');
                        form.method = 'POST';
                        if (action === 'setujui') {
                            form.action = `{{ url('validasi-mahasiswa') }}/${id}/setujui`;
                        } else {
                            form.action = `{{ url('validasi-mahasiswa') }}/${id}/tolak`;
                        }

                        const csrfToken = document.createElement('input');
                        csrfToken.type = 'hidden';
                        csrfToken.name = '_token';
                        csrfToken.value = '{{ csrf_token() }}';
                        form.appendChild(csrfToken);

                        document.body.appendChild(form);
                        form.submit();
                    }
                });
            }

            // ========== INDIVIDUAL SETUJUI BUTTONS ==========
            document.querySelectorAll('.individual-setujui-btn').forEach(btn => {
                btn.addEventListener('click', function(e) {
                    e.preventDefault();
                    const id = this.dataset.id;
                    const nama = this.dataset.nama;

                    const selectedCount = document.querySelectorAll('.row-check:checked').length;
                    if (selectedCount > 1) {
                        SwalModal.fire({
                            title: 'Perhatian!',
                            html: `Ada <strong>${selectedCount} mahasiswa</strong> yang terpilih.<br><br>
                                   Apakah Anda ingin:<br><br>
                                   <div class="space-y-2">
                                       <button id="setujuiSatu" class="w-full px-4 py-2.5 bg-emerald-500 text-white rounded-xl font-medium hover:bg-emerald-600 transition-all">
                                           ✅ Setujui Hanya <strong>${nama}</strong>
                                       </button>
                                       <button id="setujuiSemua" class="w-full px-4 py-2.5 bg-violet-500 text-white rounded-xl font-medium hover:bg-violet-600 transition-all">
                                           📋 Setujui Semua yang Terpilih (${selectedCount})
                                       </button>
                                   </div>`,
                            icon: 'info',
                            showConfirmButton: false,
                            showCancelButton: true,
                            cancelButtonText: 'Batal',
                            cancelButtonColor: '#64748b',
                            width: '450px'
                        });

                        setTimeout(() => {
                            document.getElementById('setujuiSatu')?.addEventListener('click', () => {
                                Swal.close();
                                submitIndividualAction('setujui', id, nama);
                            });
                            document.getElementById('setujuiSemua')?.addEventListener('click', () => {
                                Swal.close();
                                showBulkActionAlert('setujui', selectedCount);
                            });
                        }, 100);
                    } else {
                        submitIndividualAction('setujui', id, nama);
                    }
                });
            });

            // ========== INDIVIDUAL TOLAK BUTTONS ==========
            document.querySelectorAll('.individual-tolak-btn').forEach(btn => {
                btn.addEventListener('click', function(e) {
                    e.preventDefault();
                    const id = this.dataset.id;
                    const nama = this.dataset.nama;

                    const selectedCount = document.querySelectorAll('.row-check:checked').length;
                    if (selectedCount > 1) {
                        SwalModal.fire({
                            title: 'Perhatian!',
                            html: `Ada <strong>${selectedCount} mahasiswa</strong> yang terpilih.<br><br>
                                   Apakah Anda ingin:<br><br>
                                   <div class="space-y-2">
                                       <button id="tolakSatu" class="w-full px-4 py-2.5 bg-red-500 text-white rounded-xl font-medium hover:bg-red-600 transition-all">
                                           ❌ Tolak Hanya <strong>${nama}</strong>
                                       </button>
                                       <button id="tolakSemua" class="w-full px-4 py-2.5 bg-violet-500 text-white rounded-xl font-medium hover:bg-violet-600 transition-all">
                                           📋 Tolak Semua yang Terpilih (${selectedCount})
                                       </button>
                                   </div>`,
                            icon: 'info',
                            showConfirmButton: false,
                            showCancelButton: true,
                            cancelButtonText: 'Batal',
                            cancelButtonColor: '#64748b',
                            width: '450px'
                        });

                        setTimeout(() => {
                            document.getElementById('tolakSatu')?.addEventListener('click', () => {
                                Swal.close();
                                submitIndividualAction('tolak', id, nama);
                            });
                            document.getElementById('tolakSemua')?.addEventListener('click', () => {
                                Swal.close();
                                showBulkActionAlert('tolak', selectedCount);
                            });
                        }, 100);
                    } else {
                        submitIndividualAction('tolak', id, nama);
                    }
                });
            });
        });
    </script>

    <style>
        .animate-fade-in {
            animation: fadeIn 0.3s ease-in-out;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* Perbaikan scroll horizontal */
        .overflow-x-auto {
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }

        table {
            min-width: 640px;
            width: 100%;
        }

        @media (max-width: 768px) {
            .p-6 {
                padding: 1rem;
            }
            .px-4 {
                padding-left: 0.75rem;
                padding-right: 0.75rem;
            }
            .py-4 {
                padding-top: 0.75rem;
                padding-bottom: 0.75rem;
            }
        }
    </style>
</x-app-layout>
