$(document).ready(function () {
    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: userUrl,
            type: "GET",
            data: function (d) {
                d.keyword = $('#search').val();
                d.page = currentPage;
                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) {

                    let initials = "";
                    if (row.name) {
                        initials = row.name.split(' ').map(n => n[0]).join('').toUpperCase().substring(0, 2);
                    } else {
                        initials = "??";
                    }

                    const baseStorage = userImagePath;
                    const imgSrc = row.image ? `${baseStorage}/${row.image}` : '';

                    return `
            <div class="d-flex align-items-center profile-container">
                <div class="position-relative me-2" style="width: 40px; height: 40px;">
                    ${row.image ? `
                        <img src="${imgSrc}"
                             class="rounded-circle border"
                             style="width: 40px; height: 40px; object-fit: cover;"
                             onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
                    ` : ''}

                    <div class="avatar-circle bg-primary text-white rounded-circle d-flex align-items-center justify-content-center"
                         style="width: 40px; height: 40px; font-size: 14px; ${row.image ? 'display:none;' : 'display:flex;'}">
                        <span>${initials}</span>
                    </div>
                </div>

                <div class="ms-2">
                    <div class="fw-bold text-dark" style="line-height: 1.2;">${row.username}</div>
                    <small class="text-muted">${row.email}</small>
                </div>
            </div>
        `;
                }
            },
            {data: 'name'},
            {data: 'reports_count'},
            {
                data: 'status',
                orderable: false,
                render: function (data) {
                    if (data === 1) {
                        return `<span class="badge bg-success">Aktif</span>`;
                    } else {
                        return `<span class="badge bg-danger">Banned</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"
                        data-coreui-boundary="viewport"
                        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">

                    <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>
                </div>
            </div>
        `;
                }
            }
        ],
        columnDefs: [
            {targets: 0, className: 'text-start'},
            {targets: 3, className: 'text-start'},
            {targets: 5, className: 'text-center', width: "110px"}
        ],
    });
    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();
    });


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

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

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


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

        blockModal.show();
    });

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

        $.ajax({
            url: `/api/web/user/status/${userId}/${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
                })
            }
        });
    });
});
