<x-app-layout>
    @section('title', 'Kelola User')
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            {{ __('User Management') }}
        </h2>
    </x-slot>

    <!-- Custom Styles for DataTables Modernization -->
    <style>
        /* Force rounded corners for the 'Show entries' dropdown */
        .dataTables_wrapper .dataTables_length select {
            border-radius: 0.5rem !important; /* rounded-lg */
            border: 1px solid #d1d5db !important;
            padding: 0.375rem 2.25rem 0.375rem 0.75rem !important;
            background-position: right 0.5rem center !important;
        }

        /* Force rounded corners for the 'Search' input */
        .dataTables_wrapper .dataTables_filter input {
            border-radius: 0.5rem !important; /* rounded-lg */
            border: 1px solid #d1d5db !important;
            padding: 0.375rem 0.75rem !important;
            margin-left: 0.5rem !important;
        }

        /* Pagination buttons styling */
        .dataTables_wrapper .dataTables_paginate .paginate_button {
            border-radius: 0.375rem !important; /* rounded-md */
            border: 1px solid #e5e7eb !important;
            background: white !important;
            color: #374151 !important;
            margin: 0 0.125rem !important;
        }
        .dataTables_wrapper .dataTables_paginate .paginate_button.current {
            background: #eff6ff !important; /* blue-50 */
            border-color: #3b82f6 !important; /* blue-500 */
            color: #1d4ed8 !important; /* blue-700 */
            font-weight: 600 !important;
        }
        .dataTables_wrapper .dataTables_paginate .paginate_button:hover {
            background: #f3f4f6 !important; /* gray-100 */
            border-color: #d1d5db !important;
            color: #111827 !important;
        }

        /* Table header styling */
        table.dataTable thead th {
             border-bottom: 2px solid #e5e7eb !important;
             color: #4b5563;
             font-weight: 600;
             text-transform: uppercase;
             font-size: 0.75rem;
             letter-spacing: 0.05em;
        }

        /* Responsive styling tweaks */
        @media (max-width: 640px) {
            .dataTables_wrapper .dataTables_length,
            .dataTables_wrapper .dataTables_filter {
                text-align: left !important;
                margin-bottom: 0.5rem;
            }
            .dataTables_wrapper .dataTables_filter input {
                width: 100% !important;
                margin-left: 0 !important;
                margin-top: 0.25rem;
            }
        }
    </style>

    <link href="{{ asset('assets/css/jquery.dataTables.min.css') }}" rel="stylesheet">
    <link href="{{ asset('assets/css/responsive.dataTables.min.css') }}" rel="stylesheet">

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white overflow-hidden shadow-lg sm:rounded-xl">
                <div class="p-6 text-gray-900">

                    <div class="flex flex-col sm:flex-row justify-between items-center mb-6 gap-4">
                        <h3 class="text-xl font-bold text-gray-800 self-start sm:self-center">Daftar Admin</h3>
                        <a href="javascript:void(0)" id="createNewUser" style="background-color: #3b82f6; color: white; border-radius: 8px;" class="w-full sm:w-auto bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 px-4 rounded-lg shadow transition duration-150 ease-in-out flex items-center justify-center gap-2">
                             <span>+ Tambah Admin</span>
                        </a>
                    </div>

                    <div class="rounded-lg border border-gray-100 p-2">
                        <table class="display nowrap" id="data-table" width="100%">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">No</th>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Nama</th>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Role</th>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Email</th>
                                    <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Dibuat Pada</th>
                                    <th class="px-6 py-4 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal -->
    <div class="fixed z-50 inset-0 overflow-y-auto hidden" id="ajaxModel" aria-labelledby="modal-title" role="dialog" aria-modal="true">
        <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity backdrop-filter backdrop-blur-sm" aria-hidden="true"></div>
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
            <div class="inline-block align-bottom bg-white rounded-2xl text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                <form id="userForm" name="userForm" class="form-horizontal">
                    <div class="bg-white px-6 pt-6 pb-6 sm:p-8">
                        <div class="sm:flex sm:items-start">
                            <div class="mt-3 text-center sm:mt-0 sm:text-left w-full">
                                <h3 class="text-xl leading-6 font-bold text-gray-900 border-b pb-3 mb-4" id="modelHeading"></h3>
                                <div class="mt-2 space-y-5">
                                    <input type="hidden" name="id" id="user_id">

                                    <div>
                                        <label for="name" class="block text-sm font-medium text-gray-700 mb-1">Nama <span class="text-red-500">*</span></label>
                                        <input type="text" class="block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm px-3 py-2" id="name" name="name" placeholder="Masukkan Nama" required>
                                    </div>

                                    <div class="mt-4">
                                        <label for="email" class="block text-sm font-medium text-gray-700 mb-1">Email <span class="text-red-500">*</span></label>
                                        <input type="email" class="block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm px-3 py-2" id="email" name="email" placeholder="Masukkan Email" required>
                                    </div>

                                    <div class="mt-4">
                                        <label for="role" class="block text-sm font-medium text-gray-700 mb-1">Role <span class="text-red-500">*</span></label>
                                        <select class="block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm px-3 py-2" id="role" name="role" required>
                                            <option value="operator">Operator (Standard)</option>
                                            <option value="admin">Admin (Full Access)</option>
                                            <option value="user">User (Limited)</option>
                                        </select>
                                    </div>

                                    <div class="mt-4">
                                        <label for="password" class="block text-sm font-medium text-gray-700 mb-1">Password <span class="text-xs text-gray-500" id="password-hint">(Wajib untuk Admin baru)</span></label>
                                        <input type="password" class="block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm px-3 py-2" id="password" name="password" placeholder="Masukkan Password">
                                    </div>

                                    <div class="mt-4">
                                        <label for="password_confirmation" class="block text-sm font-medium text-gray-700 mb-1">Konfirmasi Password</label>
                                        <input type="password" class="block w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm px-3 py-2" id="password_confirmation" name="password_confirmation" placeholder="Ulangi Password">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="bg-gray-50 px-6 py-4 sm:flex sm:flex-row-reverse sm:gap-2">
                        <button type="submit" style="background-color: #2563eb; color: white; border-radius: 8px;" class="w-full inline-flex justify-center rounded-lg border border-transparent shadow px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:w-auto sm:text-sm" id="saveBtn" value="create">Simpan</button>
                        <button type="button" style="background-color: white; color: #374151; border: 1px solid #d1d5db; border-radius: 8px;" class="mt-3 w-full inline-flex justify-center rounded-lg border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:mt-0 sm:w-auto sm:text-sm" id="closeModal">Batal</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="{{ asset('assets/js/jquery.min.js') }}"></script>
    <script src="{{ asset('assets/js/jquery.dataTables.min.js') }}"></script>
    <script src="{{ asset('assets/js/dataTables.responsive.min.js') }}"></script>
    <script src="{{ asset('assets/js/sweetalert2.all.min.js') }}"></script>

    <script type="text/javascript">
        $(function () {

            // SweetAlert2 Toast Configuration
            const Toast = Swal.mixin({
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000,
                timerProgressBar: true,
                didOpen: (toast) => {
                    toast.addEventListener('mouseenter', Swal.stopTimer)
                    toast.addEventListener('mouseleave', Swal.resumeTimer)
                }
            });

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            var table = $('#data-table').DataTable({
                processing: true,
                serverSide: true,
                responsive: true,
                autoWidth: false,
                ajax: "{{ route('users.index') }}",
                columns: [
                    {data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false, searchable: false},
                    {data: 'name', name: 'name'},
                    {data: 'role_badge', name: 'role_badge'},
                    {data: 'email', name: 'email'},
                    {data: 'created_at', name: 'created_at'},
                    {data: 'action', name: 'action', orderable: false, searchable: false, className: "text-center"},
                ],
                // Add language customization for better UX
                language: {
                    "sEmptyTable":   "Tidak ada data admin yang tersedia",
                    "sProcessing":   "Sedang memproses...",
                    "sLengthMenu":   "Tampilkan _MENU_ entri",
                    "sZeroRecords":  "Tidak ditemukan data yang sesuai",
                    "sInfo":         "Menampilkan _START_ sampai _END_ dari _TOTAL_ entri",
                    "sInfoEmpty":    "Menampilkan 0 sampai 0 dari 0 entri",
                    "sInfoFiltered": "(disaring dari _MAX_ entri keseluruhan)",
                    "sInfoPostFix":  "",
                    "sSearch":       "Cari:",
                    "sUrl":          "",
                    "oPaginate": {
                        "sFirst":    "Pertama",
                        "sPrevious": "Sebelumnya",
                        "sNext":     "Selanjutnya",
                        "sLast":     "Terakhir"
                    }
                }
            });

            $('#createNewUser').click(function () {
                $('#saveBtn').val("create-user");
                $('#saveBtn').html("Simpan");
                $('#user_id').val('');
                $('#userForm').trigger("reset");
                $('#modelHeading').html("Tambah Admin Baru");
                $('#password-hint').text('(Wajib diisi)');
                $('#password').prop('required', true);
                $('#password_confirmation').prop('required', true);
                $('#role').val('operator');
                $('#ajaxModel').removeClass('hidden');
            });

            $('body').on('click', '.edit-user', function () {
                var id = $(this).data('id');
                $.get("{{ route('users.index') }}" +'/' + id +'/edit', function (data) {
                    $('#modelHeading').html("Edit Data Admin");
                    $('#saveBtn').val("edit-user");
                    $('#saveBtn').html("Update Data");
                    $('#ajaxModel').removeClass('hidden');
                    $('#user_id').val(data.id);
                    $('#name').val(data.name);
                    $('#email').val(data.email);
                    $('#role').val(data.role);

                    // Password optional when editing
                    $('#password-hint').text('(Kosongkan jika tidak ingin mengubah)');
                    $('#password').prop('required', false);
                    $('#password_confirmation').prop('required', false);
                    $('#password').val('');
                    $('#password_confirmation').val('');
                })
            });

            $('body').on('click', '#saveBtn', function (e) {
                e.preventDefault();

                // Validation Check
                if (!$('#userForm')[0].checkValidity()) {
                    $('#userForm')[0].reportValidity();
                    return;
                }

                $(this).html('Mengirim...');
                var id = $('#user_id').val();
                var url = id ? "{{ route('users.index') }}" + '/' + id : "{{ route('users.store') }}";
                var type = id ? "PUT" : "POST";

                $.ajax({
                    data: $('#userForm').serialize(),
                    url: url,
                    type: type,
                    dataType: 'json',
                    success: function (data) {
                        $('#userForm').trigger("reset");
                        $('#ajaxModel').addClass('hidden');
                        table.draw();
                        $('#saveBtn').html('Simpan');

                        Toast.fire({
                            icon: 'success',
                            title: 'Berhasil',
                            text: data.success
                        });
                    },
                    error: function (data) {
                        console.log('Error:', data);
                        $('#saveBtn').html('Simpan');

                        // Handle Validation Errors
                        let errorMessage = 'Terjadi kesalahan.';
                        if (data.status === 422) {
                             let errors = data.responseJSON.errors;
                             errorMessage = '';
                             $.each(errors, function(key, value) {
                                 errorMessage += value[0] + '<br>';
                             });
                        } else if (data.status === 403) {
                             errorMessage = data.responseJSON.error || 'Akses ditolak.';
                        }

                        Toast.fire({
                            icon: 'error',
                            title: 'Gagal',
                            html: errorMessage
                        });
                    }
                });
            });

            $('body').on('click', '.delete-user', function () {
                var id = $(this).data("id");
                Swal.fire({
                    title: 'Hapus Admin ini?',
                    text: "Data yang dihapus tidak dapat dikembalikan!",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#ef4444',
                    cancelButtonColor: '#6b7280',
                    confirmButtonText: 'Ya, Hapus!'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            type: "DELETE",
                            url: "{{ route('users.store') }}"+'/'+id,
                            success: function (data) {
                                table.draw();
                                Toast.fire({
                                    icon: 'success',
                                    title: 'Admin berhasil dihapus.'
                                });
                            },
                            error: function (data) {
                                console.log('Error:', data);
                                let message = 'Gagal menghapus data.';
                                if (data.status === 403) {
                                    message = data.responseJSON.error;
                                }
                                Toast.fire({
                                    icon: 'error',
                                    title: message
                                });
                            }
                        });
                    }
                })
            });

            $('body').on('click', '#closeModal', function() {
                $('#ajaxModel').addClass('hidden');
            });
        });
    </script>
</x-app-layout>
