$(document).ready(function() {
    $.ajaxSetup({
        headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
    });
    
    const sessionModal = new bootstrap.Modal(document.getElementById('sessionModal'));
    
    let currentPage = 1;
    let searchQuery = '';
    let searchTimer;

    fetchSessions(currentPage, searchQuery);

    function fetchSessions(page, search = '') {
        $.ajax({
            type: "GET",
            url: base_url + `/fetch-client-users?page=${page}&search=${encodeURIComponent(search)}`,
            dataType: "json",
            success: function(response) {
                $('#clientUsersTableBody').html("");
                
                if (response.sessions.data && response.sessions.data.length > 0) {
                    $.each(response.sessions.data, function(key, item) {
                        $('#clientUsersTableBody').append(`
                            <tr>
                                <td>${item.id}</td>
                                <td>${item.email}</td>
                                <td>${item.role}</td>
                                <td>
                                    <button class="btn btn-success btn-sm editBtn" value="${item.id}">Edit</button>
                                    <button class="btn btn-danger btn-sm deleteBtn" value="${item.id}">Delete</button>
                                </td>
                            </tr>
                        `);
                    });

                    let from = response.sessions.from;
                    let to = response.sessions.to;
                    let total = response.sessions.total;
                    $('#paginationCounter').html(`Showing ${from} to ${to} of ${total} results`);
                } else {
                    $('#clientUsersTableBody').html("<tr><td colspan='4' class='text-center'>No users found</td></tr>");
                    $('#paginationCounter').html('Showing 0 to 0 of 0 results');
                }
                
                renderPagination(response);
            }
        });
    }

    $('#searchInput').on('keyup', function() {
        clearTimeout(searchTimer);
        searchQuery = $(this).val();
        
        // Wait 500ms after the user stops typing to trigger the request
        searchTimer = setTimeout(function() {
            currentPage = 1; // Reset to page 1 for a brand new search
            fetchSessions(currentPage, searchQuery);
        }, 500);
    });

    $(document).on('click', '.page-link', function(e) {
        e.preventDefault();
        
        if ($(this).parent().hasClass('disabled')) {
            return false;
        }

        let page = $(this).data('page');
        
        if (page > 0) {
            currentPage = page;
            fetchSessions(currentPage, searchQuery);
        }
    });

    function renderPagination(response) {
        let linksHtml = '';
        currentPage = response.sessions.current_page;
        let lastPage = response.sessions.last_page;

        let prevDisabled = currentPage === 1 ? 'disabled' : '';
        let prevTabIndex = currentPage === 1 ? 'tabindex="-1"' : '';
        
        linksHtml += `
            <li class="page-item ${prevDisabled}">
                <a class="page-link" href="#" data-page="${currentPage - 1}" ${prevTabIndex}>Previous</a>
            </li>`;


        for (let i = 1; i <= lastPage; i++) {
            let activeClass = currentPage === i ? 'active' : '';
            let activeAria = currentPage === i ? 'aria-current="page"' : '';
            
            linksHtml += `
                <li class="page-item ${activeClass}" ${activeAria}>
                    <a class="page-link" href="#" data-page="${i}">${i}</a>
                </li>`;
        }
        let nextDisabled = currentPage === lastPage ? 'disabled' : '';
        let nextTabIndex = currentPage === lastPage ? 'tabindex="-1"' : '';
        
        linksHtml += `
            <li class="page-item ${nextDisabled}">
                <a class="page-link" href="#" data-page="${currentPage + 1}" ${nextTabIndex}>Next</a>
            </li>`;

        $('#paginationLinks').html(linksHtml);
    }



    $(document).on('click', '.page-link', function(e) {
        e.preventDefault();
        let page = $(this).data('page');
        
        if (page > 0) {
            fetchSessions(page);
        }
    });
    $('#addNewBtn').click(function() {
        $('#sessionForm')[0].reset();
        $('#sessionId').val('');
        $('#modalTitle').text('Add Session');
        sessionModal.show();
    });

    $('#sessionForm').submit(function(e) {
        e.preventDefault();
        
        let id = $('#sessionId').val();
        let data = {
            email: $('#email').val(),
            role: $('#role').val(),
            password: $('#password').val()
        };

        let url = id ? base_url + `/client-users/${id}` : base_url + '/client-users';
        let type = id ? "PUT" : "POST";

        $.ajax({
            type: type,
            url: url,
            data: data,
            dataType: "json",
            success: function(response) {
                sessionModal.hide();
                showAlert(response.message, 'success');
                fetchSessions(currentPage);
            },
            error: function(xhr) {
                let errors = xhr.responseJSON.errors;
                if(errors.email) showAlert(errors.email, 'danger');
                if(errors.role) showAlert(errors.role, 'danger');
            }
        });
    });

    $(document).on('click', '.editBtn', function() {
        let id = $(this).val();
        $.get(base_url + `/client-users/${id}/edit`, function(response) {
            $('#sessionId').val(response.session.id);
            $('#email').val(response.session.email);
            $('#role').val(response.session.role);
            $('#modalTitle').text('Edit Session');
            sessionModal.show();
        });
    });

    $(document).on('click', '.deleteBtn', function() {
        let id = $(this).val();
        if(confirm('Are you sure you want to delete this session?')) {
            $.ajax({
                type: "DELETE",
                url: base_url + `/client-users/${id}`,
                success: function(response) {
                    showAlert(response.message, 'success');
                    fetchSessions(currentPage); // Stay on current page
                }
            });
        }
    });

    function showAlert(message, type) {
        $('#alertArea').html(`
            <div class="alert alert-${type} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        `);
    }
});