<x-app-layout>
    <div class="mb-12">
        <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-6 mb-8">
            <div>
                <h1 class="text-4xl font-black tracking-tight dark:text-white">
                    <span class="bg-gradient-to-r from-violet-600 to-indigo-600 bg-clip-text text-transparent">
                        Aturan Bonus RAP
                    </span>
                </h1>
                <p class="text-slate-500 dark:text-slate-400 text-sm mt-1">
                    <i data-lucide="settings" class="w-4 h-4 inline mr-2"></i>
                    Kelola aturan bonus berdasarkan jumlah mahasiswa yang direkrut
                </p>
            </div>
            <a href="{{ route('rap.index') }}"
                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 hover:bg-slate-50 transition-all flex items-center gap-2">
                <i data-lucide="arrow-left" class="w-4 h-4"></i>
                Kembali
            </a>
        </div>

        <!-- Form Tambah Rule -->
        <div class="bg-white dark:bg-[#1a1a2e] rounded-xl border border-slate-200 dark:border-white/5 p-6 mb-6">
            <h3 class="font-semibold text-lg mb-4">➕ Tambah Aturan Bonus Baru</h3>
            <form action="{{ route('rap.bonus.store') }}" method="POST" class="grid grid-cols-1 md:grid-cols-5 gap-4">
                @csrf
                <input type="text" name="nama_rule" placeholder="Nama Rule (contoh: Bronze)"
                    class="px-3 py-2 bg-white dark:bg-gray-800 border border-slate-200 rounded-lg text-sm" required>
                <input type="number" name="min_mahasiswa" placeholder="Min Mahasiswa"
                    class="px-3 py-2 bg-white dark:bg-gray-800 border border-slate-200 rounded-lg text-sm" required>
                <input type="number" name="max_mahasiswa" placeholder="Max Mahasiswa (kosongkan jika unlimited)"
                    class="px-3 py-2 bg-white dark:bg-gray-800 border border-slate-200 rounded-lg text-sm">
                <input type="number" name="nominal_bonus" placeholder="Nominal Bonus"
                    class="px-3 py-2 bg-white dark:bg-gray-800 border border-slate-200 rounded-lg text-sm" required>
                <button type="submit"
                    class="px-4 py-2 bg-gradient-to-r from-violet-600 to-indigo-700 text-white rounded-lg text-sm font-medium">
                    <i data-lucide="plus" class="w-4 h-4 inline mr-1"></i>
                    Tambah Rule
                </button>
            </form>
        </div>

        <!-- Daftar Rules -->
        <div class="bg-white dark:bg-[#1a1a2e] rounded-xl border border-slate-200 dark:border-white/5 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead>
                        <tr class="bg-slate-50/50 dark:bg-white/5 border-b">
                            <th class="text-left py-3 px-4 text-xs font-semibold text-slate-500 uppercase">No</th>
                            <th class="text-left py-3 px-4 text-xs font-semibold text-slate-500 uppercase">Nama Rule
                            </th>
                            <th class="text-left py-3 px-4 text-xs font-semibold text-slate-500 uppercase">Range
                                Mahasiswa</th>
                            <th class="text-left py-3 px-4 text-xs font-semibold text-slate-500 uppercase">Nominal Bonus
                            </th>
                            <th class="text-left py-3 px-4 text-xs font-semibold text-slate-500 uppercase">Status</th>
                            <th class="text-left py-3 px-4 text-xs font-semibold text-slate-500 uppercase">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($rules as $index => $rule)
                            <tr class="border-b hover:bg-slate-50/50 dark:hover:bg-white/5"
                                id="row-{{ $rule->id }}">
                                <td class="py-3 px-4">{{ $loop->iteration }}</td>
                                <td class="py-3 px-4 font-medium">{{ $rule->nama_rule }}</td>
                                <td class="py-3 px-4">
                                    {{ $rule->min_mahasiswa }} - {{ $rule->max_mahasiswa ?: '∞' }}
                                </td>
                                <td class="py-3 px-4 font-mono text-emerald-600">
                                    Rp {{ number_format($rule->nominal_bonus, 0, ',', '.') }}
                                </td>
                                <td class="py-3 px-4">
                                    <span
                                        class="px-2 py-1 text-xs rounded-full {{ $rule->is_active == 'aktif' ? 'bg-green-500/10 text-green-600' : 'bg-red-500/10 text-red-600' }}">
                                        {{ $rule->is_active == 'aktif' ? 'Aktif' : 'Nonaktif' }}
                                    </span>
                                </td>
                                <td class="py-3 px-4">
                                    <div class="flex items-center gap-2">
                                        <button type="button" onclick="openEditModal({{ $rule->id }})"
                                            class="p-1.5 text-blue-600 hover:bg-blue-50 rounded-lg transition">
                                            <i data-lucide="edit" class="w-4 h-4"></i>
                                        </button>
                                        <form action="{{ route('rap.bonus.toggle', $rule->id) }}" method="POST"
                                            class="inline toggle-form" data-id="{{ $rule->id }}">
                                            @csrf
                                            <button type="submit"
                                                class="p-1.5 text-yellow-600 hover:bg-yellow-50 rounded-lg transition">
                                                <i data-lucide="{{ $rule->is_active == 'aktif' ? 'toggle-right' : 'toggle-left' }}"
                                                    class="w-4 h-4"></i>
                                            </button>
                                        </form>
                                        <form action="{{ route('rap.bonus.destroy', $rule->id) }}" method="POST"
                                            class="inline delete-form" data-id="{{ $rule->id }}"
                                            data-name="{{ $rule->nama_rule }}">
                                            @csrf
                                            @method('DELETE')
                                            <button type="submit"
                                                class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition">
                                                <i data-lucide="trash-2" class="w-4 h-4"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Info Penggunaan -->
        <div class="mt-6 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-xl border border-blue-200 dark:border-blue-500/20">
            <h4 class="font-semibold text-blue-800 dark:text-blue-300 flex items-center gap-2">
                <i data-lucide="info" class="w-4 h-4"></i>
                Informasi
            </h4>
            <ul class="mt-2 text-sm text-blue-700 dark:text-blue-400 space-y-1">
                <li>• Rule akan dieksekusi berdasarkan urutan dari jumlah mahasiswa tertinggi ke terendah</li>
                <li>• Jika max_mahasiswa dikosongkan, berarti tidak ada batas atas (unlimited)</li>
                <li>• Pastikan tidak ada tumpang tindih range antar rule</li>
                <li>• Rule yang tidak aktif tidak akan digunakan dalam perhitungan bonus</li>
            </ul>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            lucide.createIcons();

            // SweetAlert untuk success/error dari session
            @if (session('success'))
                Swal.fire({
                    title: 'Berhasil!',
                    text: '{{ session('success') }}',
                    icon: 'success',
                    confirmButtonText: 'Mengerti',
                    timer: 3000,
                    timerProgressBar: true
                });
            @endif

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

            // Konfirmasi untuk form delete
            document.querySelectorAll('.delete-form').forEach(form => {
                form.addEventListener('submit', function(e) {
                    e.preventDefault();
                    const ruleName = this.dataset.name || 'aturan ini';

                    Swal.fire({
                        title: 'Hapus Aturan?',
                        html: `Anda akan menghapus aturan bonus <strong>${ruleName}</strong>?`,
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonColor: '#ef4444',
                        cancelButtonColor: '#6b7280',
                        confirmButtonText: 'Ya, Hapus!',
                        cancelButtonText: 'Batal'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            form.submit();
                        }
                    });
                });
            });

            // Konfirmasi untuk toggle status
            document.querySelectorAll('.toggle-form').forEach(form => {
                form.addEventListener('submit', function(e) {
                    e.preventDefault();
                    const formElement = this;

                    Swal.fire({
                        title: 'Ubah Status?',
                        text: 'Anda akan mengubah status aturan bonus ini.',
                        icon: 'question',
                        showCancelButton: true,
                        confirmButtonColor: '#f59e0b',
                        cancelButtonColor: '#6b7280',
                        confirmButtonText: 'Ya, Ubah!',
                        cancelButtonText: 'Batal'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            formElement.submit();
                        }
                    });
                });
            });
        });

        // Fungsi untuk edit modal
        function openEditModal(id) {
            // Fetch data dari server - PASTIKAN URL NYA BENAR
            fetch(`/rap/bonus-rules/${id}/edit`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    Swal.fire({
                        title: 'Edit Aturan Bonus',
                        html: `
                    <form id="editBonusForm" class="space-y-3 text-left">
                        <div>
                            <label class="block text-sm font-medium mb-1">Nama Rule</label>
                            <input type="text" id="edit_nama_rule" class="w-full px-3 py-2 border rounded-lg" value="${data.nama_rule}">
                        </div>
                        <div>
                            <label class="block text-sm font-medium mb-1">Min Mahasiswa</label>
                            <input type="number" id="edit_min_mahasiswa" class="w-full px-3 py-2 border rounded-lg" value="${data.min_mahasiswa}">
                        </div>
                        <div>
                            <label class="block text-sm font-medium mb-1">Max Mahasiswa (kosongkan jika unlimited)</label>
                            <input type="number" id="edit_max_mahasiswa" class="w-full px-3 py-2 border rounded-lg" value="${data.max_mahasiswa || ''}">
                        </div>
                        <div>
                            <label class="block text-sm font-medium mb-1">Nominal Bonus</label>
                            <input type="number" id="edit_nominal_bonus" class="w-full px-3 py-2 border rounded-lg" value="${data.nominal_bonus}">
                        </div>
                        <div>
                            <label class="block text-sm font-medium mb-1">Status</label>
                            <select id="edit_is_active" class="w-full px-3 py-2 border rounded-lg">
                                <option value="aktif" ${data.is_active === 'aktif' ? 'selected' : ''}>Aktif</option>
                                <option value="nonaktif" ${data.is_active === 'nonaktif' ? 'selected' : ''}>Nonaktif</option>
                            </select>
                        </div>
                    </form>
                `,
                        showCancelButton: true,
                        confirmButtonText: 'Simpan',
                        cancelButtonText: 'Batal',
                        preConfirm: () => {
                            const nama_rule = document.getElementById('edit_nama_rule').value;
                            const min_mahasiswa = document.getElementById('edit_min_mahasiswa').value;
                            const max_mahasiswa = document.getElementById('edit_max_mahasiswa').value;
                            const nominal_bonus = document.getElementById('edit_nominal_bonus').value;
                            const is_active = document.getElementById('edit_is_active').value;

                            if (!nama_rule) {
                                Swal.showValidationMessage('Nama Rule harus diisi');
                                return false;
                            }
                            if (!min_mahasiswa) {
                                Swal.showValidationMessage('Min Mahasiswa harus diisi');
                                return false;
                            }
                            if (!nominal_bonus) {
                                Swal.showValidationMessage('Nominal Bonus harus diisi');
                                return false;
                            }

                            return {
                                nama_rule: nama_rule,
                                min_mahasiswa: min_mahasiswa,
                                max_mahasiswa: max_mahasiswa || null,
                                nominal_bonus: nominal_bonus,
                                is_active: is_active,
                                _method: 'PUT'
                            };
                        }
                    }).then((result) => {
                        if (result.isConfirmed) {
                            // Gunakan POST dengan _method PUT
                            fetch(`/rap/bonus-rules/${id}`, {
                                    method: 'POST',
                                    headers: {
                                        'Content-Type': 'application/json',
                                        'Accept': 'application/json',
                                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                            .content
                                    },
                                    body: JSON.stringify(result.value)
                                })
                                .then(response => response.json())
                                .then(data => {
                                    if (data.success) {
                                        Swal.fire('Berhasil!', data.message || 'Rule berhasil diperbarui',
                                                'success')
                                            .then(() => location.reload());
                                    } else {
                                        Swal.fire('Gagal!', data.message || 'Terjadi kesalahan', 'error');
                                    }
                                })
                                .catch(error => {
                                    console.error('Error:', error);
                                    Swal.fire('Gagal!', 'Terjadi kesalahan pada server: ' + error.message,
                                        'error');
                                });
                        }
                    });
                })
                .catch(error => {
                    console.error('Fetch error:', error);
                    Swal.fire('Error!', 'Gagal mengambil data rule: ' + error.message, 'error');
                });
        }
    </script>
</x-app-layout>
