$(document).ready(function() {

    new SlimSelect({
        select: '#role'
    })

    let currentPage = 1;
    let totalPage = 1;
    const btn = document.getElementById('filterToggleBtn');
    const box = document.getElementById('customFilterBox');
    const icon = btn.querySelector('.rotate-icon');

    btn.addEventListener('click', function () {
        const isOpen = box.classList.toggle('open');
        icon.classList.toggle('rotated', isOpen);
        btn.classList.toggle('expanded', isOpen); // ⬅️ ini tambahan
    });

    let table = $('#empTable').DataTable({
        dom:'t',
        processing: true,
        serverSide: true,
        searching: false,
        lengthChange: false,
        ordering: false,
        info: false,
        ajax: {
            url: tableUrl,
            type: "GET",
            data: function (d) {
                d.keyword = $('#search').val();
                d.page = currentPage;
                d.role = $('#role').val();
                d.status = $('#status').val();
                d.sort_by = $('#sortBy').val();
                d.sort_dir = $('#sortDir').val();
                d.size = $('#dLength').val();
            }
        },
        pageLength: $('#dLength').val(),
        columns: [
            {
                data: null,
                orderable: false,
                render: function (data, type, row, meta) {
                    var currentPage = meta.settings.json.pagination.current_page;
                    var perPage = meta.settings.json.pagination.per_page;

                    return (currentPage - 1) * perPage + meta.row + 1;
                }
            },
            {
                data: null ,
                render: function(data, type, row) {
                    return `
                    <div class="d-flex align-items-center">
                        <div class="avatar-circle bg-primary text-white me-2">
                            <span>${row.name.split(' ').map(n => n[0]).join('')}</span>
                        </div>
                        <div>
                            <div class="fw-semibold">${row.username}</div>
                            <small class="text-muted">${row.email}</small>
                        </div>
                    </div>
                `;
                }
            },
            { data: 'name'},
            { data: 'role.name'},
            {
                data: 'status',
                orderable: false,
                render: function(data) {
                    if(data === 1) {
                        return `<span class="badge bg-success">Aktif</span>`;
                    } else if(data === 0) {
                        return `<span class="badge bg-success">Nonaktif</span>`;
                    } else {
                        return `<span class="badge bg-danger">Blokir</span>`;
                    }
                }
            },
            {
                data: 'id',
                orderable: false,
                render: function(id, type, row) {
                    const isAktif = row.status === 1;

                    const actionText = isAktif ? 'Blokir' : 'Aktifkan';
                    const actionIcon = isAktif ? 'bi-ban text-danger' : 'bi-check2-circle text-success';
                    return `
        <div class="dropdown text-center">
            <button class="btn btn-sm action-btn action-btn-sm border-0 bg-transparent"
                    data-coreui-toggle="dropdown"
                    aria-expanded="false">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="16" height="16">
                    <circle cx="256" cy="53.333" r="53.333"/>
                    <circle cx="256" cy="256" r="53.333"/>
                    <circle cx="256" cy="458.667" r="53.333"/>
                </svg>
            </button>

            <div class="dropdown-menu dropdown-menu-end shadow-sm">
                <a class="dropdown-item small" href="/user-management/admin/edit/${id}">
                    <i class="bi bi-pencil-square me-2"></i> Edit
                </a>

                <button class="dropdown-item small text-danger btn-delete" data-id="${id}">
                    <i class="bi bi-trash me-2"></i> Hapus
                </button>

                <button class="dropdown-item small btn-status" data-id="${id}" data-status="${row.status}" data-name="${row.name}">
                        <i class="bi ${actionIcon} me-2"></i> ${actionText}
                    </button>
                    <button class="dropdown-item small text-danger btn-reset" data-id="${id}">
                    <i class="bi bi-key-fill me-2"></i> Reset Kata sandi
                </button>

            </div>
        </div>
    `;
                }
            }
        ],
        columnDefs: [
            { targets: 0, className: 'text-start', width: "70px"}, // kolom No
            { targets: 5, className: 'text-center' ,width: "110px"}  // kolom Actions biar tombol rapi
        ],
    });
    table.on('xhr', function(e, settings, json) {
        if (!json) return;

        console.log(json);

        $('#start').text(json.pagination.from ?? 0);
        $('#end').text(json.pagination.to ?? 0);
        $('#total').text(json.pagination.total ?? 0);

        totalPage = json.data.last_page;

        let pagination = $('#custom-pagination');
        pagination.empty();

        let prevClass = json.pagination.current_page == 1 ? 'disabled' : '';
        pagination.append(`<li class="page-item ${prevClass}">
        <a class="page-link" href="#" data-page="prev">Previous</a>
    </li>`);

        for (let i = 1; i <= json.pagination.last_page; i++) {
            let activeClass = json.pagination.current_page == i ? 'active' : '';
            pagination.append(`<li class="page-item ${activeClass}">
            <a class="page-link" href="#" data-page="${i}">${i}</a>
        </li>`);
        }

        let nextClass = json.pagination.current_page == json.data.last_page ? 'disabled' : '';
        pagination.append(`<li class="page-item ${nextClass}">
        <a class="page-link" href="#" data-page="next">Next</a>
    </li>`);
    });
    $(document).on('click', '#custom-pagination a', function(e) {
        e.preventDefault();
        let page = $(this).data('page');

        if (page === 'prev' && currentPage > 1) currentPage--;
        else if (page === 'next' && currentPage < totalPage) currentPage++;
        else if (!isNaN(page)) currentPage = parseInt(page);
        else return;

        table.ajax.reload(null, false);
    });



    $('#search').on('keyup', function() {
        table.ajax.reload();
    });

    $('#dLength').on('change', function() {
        table.page.len(this.value).draw();
    });

    $('#sortBy').on('change', function() {
        table.ajax.reload();
    });

    $('#sortDir').on('change', function() {
        table.ajax.reload();
    });

    $('#role').on('change', function() {
        table.ajax.reload();
    });

    $('#status').on('change', function() {
        table.ajax.reload();
    });

    let deleteId = null;
    let deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));

    $(document).on('click', '.btn-delete', function () {
        deleteId = $(this).data('id');
        deleteModal.show();
    });

    $('#confirmDelete').on('click', function () {
        if (!deleteId) return;

        $.ajax({
            url: `/api/web/admin/delete/${deleteId}`,
            type: 'POST',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function (res) {
                const successMessage = res.message || 'Data berhasil dihapus';
                deleteModal.hide();
                table.ajax.reload(null, false);
                const Toast = Swal.mixin({
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 2000,
                    didOpen: (toast) => {
                        toast.addEventListener('mouseenter', Swal.stopTimer)
                        toast.addEventListener('mouseleave', Swal.resumeTimer)
                    }
                })

                Toast.fire({
                    icon: 'success',
                    title: successMessage
                })
            },
            error: function (xhr) {
                deleteModal.hide();
                let message = 'Gagal menghapus data';
                if (xhr.responseJSON) {
                    if (xhr.responseJSON.message) {
                        message = xhr.responseJSON.message;
                    }
                }

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

                Toast.fire({
                    icon: 'error',
                    title: message
                })
            }
        });
    });

    let adminId = null;
    let status = null;
    let blockModal = new bootstrap.Modal(document.getElementById('blockModal'));
    let resetModal = new bootstrap.Modal(document.getElementById('resetModal'));

    $(document).on('click', '.btn-status', function () {
        adminId = $(this).data('id');
        status = $(this).data('status');


        $('#modalTitleBlock').text(status === 1 ? `Blokir User ${$(this).data('name')}` : `Aktifkan User ${$(this).data('name')}`);

        blockModal.show();
    });

    $(document).on('click', '.btn-reset', function () {
        adminId = $(this).data('id');
        resetModal.show();
    });

    $('#confirmBlock').on('click', function () {
        if (!adminId) return;

        $.ajax({
            url: `/api/web/admin/status/${adminId}/${status}`,
            type: 'POST',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function (res) {
                const successMessage = res.message || 'Perubahan berhasil';
                blockModal.hide();
                table.ajax.reload(null, false);
                const Toast = Swal.mixin({
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 2000,
                    didOpen: (toast) => {
                        toast.addEventListener('mouseenter', Swal.stopTimer)
                        toast.addEventListener('mouseleave', Swal.resumeTimer)
                    }
                })

                Toast.fire({
                    icon: 'success',
                    title: successMessage
                })
            },
            error: function (xhr) {
                deleteModal.hide();
                let message = 'Gagal perubahan data';
                if (xhr.responseJSON) {
                    if (xhr.responseJSON.message) {
                        message = xhr.responseJSON.message;
                    }
                }

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

                Toast.fire({
                    icon: 'error',
                    title: message
                })
            }
        });
    });

    $('#confirmReset').on('click', function () {
        if (!adminId) return;

        $.ajax({
            url: `/api/web/admin/reset/${adminId}`,
            type: 'POST',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function (res) {
                const successMessage = res.message || 'Perubahan berhasil';
                resetModal.hide();
                const Toast = Swal.mixin({
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 2000,
                    didOpen: (toast) => {
                        toast.addEventListener('mouseenter', Swal.stopTimer)
                        toast.addEventListener('mouseleave', Swal.resumeTimer)
                    }
                })

                Toast.fire({
                    icon: 'success',
                    title: successMessage
                })
            },
            error: function (xhr) {
                deleteModal.hide();
                let message = 'Gagal perubahan data';
                if (xhr.responseJSON) {
                    if (xhr.responseJSON.message) {
                        message = xhr.responseJSON.message;
                    }
                }

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

                Toast.fire({
                    icon: 'error',
                    title: message
                })
            }
        });
    });
});
