const { __, _x, _n, sprintf } = wp.i18n;

let userPerPage = 10;           // Default Users per page is 10
let selectedIds = [];           // Stores IDs of users whose checkboxes are selected
let orderBy = "user_login";     // Default table order by user_login
let orderDirection = "ASC";     // Default table order direction is ascending
let search_key = "";            // Global variable to get store search value
let userRole = "all";           // Table fetch all users as per default

// Permissions allowed against a user
let is_admin = author_kit_profile_table_vars.is_admin;
let is_edit_users = author_kit_profile_table_vars.is_edit_users;
let is_manage_options = author_kit_profile_table_vars.is_manage_options;
let current_user_id = author_kit_profile_table_vars.current_user_id;
let update_author_profile_nonce = author_kit_profile_table_vars.update_author_profile_nonce;



document.addEventListener('DOMContentLoaded', function () {
    initialize();
});

function initialize() {
    // Call fetch_data on page load
    fetch_data();

    get_total_authors_by_role();

    initialize_sorting()
    on_change_option();
    on_click_next();
    on_click_previous();
    author_profile_filter_active_tab();

    // Debounced search function
    const debouncedLoadProfileTable = debounce(() => fetch_data(), 750);

    // Search user with debouncing
    document.getElementById('users-profile-search').addEventListener('keyup', function () {
        search_key = this.value;
        debouncedLoadProfileTable();
    });
}

// Debounce function to limit frequent calls
function debounce(func, delay) {
    let timer;
    return function (...args) {
        clearTimeout(timer);
        timer = setTimeout(() => func.apply(this, args), delay);
    };
}

// Fetch data to populate the table
function fetch_data(page_id = 1) {

    reset_selection();
    // Get the loader element (assuming it exists in your HTML)
    const loader = document.getElementById("loader");

    // Show the loader before making the AJAX request
    loader.style.display = "block";

    fetch(author_kit_profile_table_vars.ajax_url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        body: new URLSearchParams({
            action: 'author_kit_get_user_data',
            nonce: author_kit_profile_table_vars.nonce,
            pageId: page_id,
            order_by: orderBy,
            order_direction: orderDirection,
            limit: userPerPage,
            role: userRole,
            search: search_key,


        })
    })
        .then(response => response.json())
        .then(data => {
            // Authors data is formed by calling this function
            populate_table(data.user_data, data.pagination_data);
        })
        .catch(error => {
            // Hide the loader if there's an error
            loader.style.display = "none";

            show_author_kit_toast(__('Error in Loading Author Profile Table', 'author-kit'), 'error')
        });

}

function reset_selection() {
    selectedIds = [];

    const tableBody = document.querySelector("#profileTable tbody");
    tableBody.innerHTML = "";


    const selectAllCheckbox = document.getElementById('select-all');
    if (selectAllCheckbox && selectAllCheckbox.checked) {
        selectAllCheckbox.checked = false;
    }
    document.getElementById('switch-container').style.display = 'none';
}

function get_total_authors_by_role() {
    // Prepare the data to send with the AJAX request
    const data = {
        action: 'author_kit_get_total_authors', // The action corresponds to the PHP function hooked to wp_ajax_
        nonce: author_kit_profile_table_vars.nonce // Assuming nonce is localized in the JS file
    };

    // Send the AJAX request using fetch
    fetch(author_kit_profile_table_vars.ajax_url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams(data)
    })
        .then(response => response.json())
        .then(data => {

            if (data.success) {
                // Get the filter-tabs element
                const filterTabs = document.getElementById('filter-tabs');
                if (!filterTabs) {
                    show_author_kit_toast(__('Filter Tabs Not Found', "author-kit"), 'error');
                    return;
                }

                // Clear existing content (optional, based on your requirement)
                filterTabs.innerHTML = '';

                // Loop through each role in the response and create a tab
                Object.keys(data.data).forEach(role => {
                    // Create the role paragraph element
                    const roleTab = document.createElement('p');
                    roleTab.id = `${role}-users`; // Set a unique ID for each role
                    roleTab.textContent = `${role.charAt(0).toUpperCase() + role.slice(1)}`; // Add role name and user count
                    roleTab.onclick = () => {
                        // Add your onclick logic here
                        userRole = role;
                        fetch_data(1);
                    };

                    // Add a span for additional information (if required)
                    const roleInfo = document.createElement('span');
                    roleInfo.id = `${role}-information`; // Unique ID for the span
                    roleInfo.textContent = ` (${data.data[role]}) `; // You can customize this content as needed

                    // Append the role tab and its span to the filter-tabs div
                    filterTabs.appendChild(roleTab);
                    filterTabs.appendChild(roleInfo);
                });
            } else {
                show_author_kit_toast(__('Error in Loading Filter Tabs User Count', 'author-kit'), 'error');
            }
        })
        .catch(error => show_author_kit_toast(__('Failed to Load Filter Tabs User Count', 'author-kit'), 'error'));
}

// Function to populate the table
function populate_table(data, pagination_data) {

    try {
        const tbody = document.querySelector('#profileTable tbody');
        tbody.innerHTML = ''; // Clear existing data

        if (data.length != 0) {

            const fragment = document.createDocumentFragment(); // Use DocumentFragment to minimize reflows

            data.forEach(item => {
                const row = document.createElement("tr");

                // Checkbox Cell
                const checkboxCell = document.createElement("td");
                const checkbox = document.createElement("input");
                checkbox.type = "checkbox";
                checkbox.className = "row-checkbox";
                checkbox.value = item.ID;
                if (is_edit_users || item.ID == current_user_id) {
                    checkboxCell.appendChild(checkbox);
                }
                row.appendChild(checkboxCell);

                // Avatar & Name Cell
                const avatarCell = document.createElement("td");
                const avatarWrapper = document.createElement("div");
                avatarWrapper.id = "first-row-avatar-name-style";

                const avatarDiv = document.createElement("div");
                const avatarImg = document.createElement("img");
                avatarImg.src = item.avatar;
                avatarImg.className = "avatar";
                avatarImg.id = "avatar-img";
                avatarImg.alt = item.display_name;
                avatarDiv.appendChild(avatarImg);

                const nameContainer = document.createElement("div");
                const nameDiv = document.createElement("div");
                nameDiv.textContent = item.display_name;
                const usernameSpan = document.createElement("span");
                usernameSpan.id = "user-name-display";
                usernameSpan.textContent = `@${item.username}`;
                nameContainer.appendChild(nameDiv);
                nameContainer.appendChild(usernameSpan);

                avatarWrapper.appendChild(avatarDiv);
                avatarWrapper.appendChild(nameContainer);
                avatarCell.appendChild(avatarWrapper);
                row.appendChild(avatarCell);

                // Role Cell
                const roleCell = document.createElement("td");
                const roleBtn = document.createElement("button");
                roleBtn.id = "blue-btn";
                roleBtn.textContent = item.role;
                roleCell.appendChild(roleBtn);
                row.appendChild(roleCell);

                // Bio Widget Cell
                const bioWidgetCell = document.createElement("td");
                const bioWidgetSwitch = document.createElement("input");
                bioWidgetSwitch.type = "checkbox";
                bioWidgetSwitch.className = "bio-widget-switch";
                bioWidgetSwitch.dataset.userId = item.ID;
                bioWidgetSwitch.checked = item.bio_widget;
                if (is_edit_users || item.ID == current_user_id) {
                    bioWidgetSwitch.disabled = false;
                } else {
                    bioWidgetSwitch.disabled = true;
                }
                const bioWidgetLabel = document.createElement("label");
                bioWidgetLabel.className = "switch";
                const bioWidgetSpan = document.createElement("span");
                bioWidgetSpan.className = "slider round";

                bioWidgetLabel.appendChild(bioWidgetSwitch);
                bioWidgetLabel.appendChild(bioWidgetSpan);
                bioWidgetCell.appendChild(bioWidgetLabel);
                row.appendChild(bioWidgetCell);

                // Edit Profile Cell
                const actionsCell = document.createElement("td");
                const dropdown = document.createElement("div");
                dropdown.className = "dropdown";

                const editButton = document.createElement("button");
                editButton.className = "dropdown-toggle";
                editButton.innerHTML = "<i class='fa-regular fa-pen-to-square'></i>";
                if (is_edit_users || item.ID == current_user_id) {
                    const editLink = document.createElement("a");
                    editLink.href = `admin.php?page=author-kit-update-author-profile&user_id=${item.ID}&action=edit&update-author-profile-nonce=${update_author_profile_nonce}`;
                    editLink.appendChild(editButton);
                    dropdown.appendChild(editLink);
                } else {
                    editButton.disabled = true;
                    dropdown.appendChild(editButton);
                }

                actionsCell.appendChild(dropdown);
                row.appendChild(actionsCell);

                fragment.appendChild(row);
            });

            tbody.appendChild(fragment); // Batch insert all rows at once


            select_boxes_functionality();

            // Call the synchronization function at the end of populate Table
            switch_boxes_functionality();

        } else {
            const row = document.createElement("tr");
            const cell = document.createElement("td");
            const paragraph = document.createElement("p");

            paragraph.textContent = __("No authors found. Please try a different search keyword", "author-kit");
            cell.setAttribute("colspan", "5"); // our table has 5 columns
            cell.style.textAlign = "center";
            cell.style.padding = "20px";

            cell.appendChild(paragraph);
            row.appendChild(cell);
            tbody.appendChild(row);
        }

        // Add Pagination *****************************************************************


        const pageNumbersSpan = document.getElementById('pageNumbers');
        const prevPageButton = document.getElementById('prevPage');
        const nextPageButton = document.getElementById('nextPage');

        /* translators: 1: current page number, 2: total number of pages */
        pageNumbersSpan.innerHTML = sprintf(
            __('Page %1$s of %2$s', 'author-kit'),
            pagination_data.total_pages != 0 ? pagination_data.current_page : 0,
            pagination_data.total_pages
        );
        prevPageButton.disabled = pagination_data.current_page === 1;
        nextPageButton.disabled = pagination_data.current_page === pagination_data.total_pages || pagination_data.total_pages === 0;

        if (pagination_data.current_page == 1) {
            prevPageButton.setAttribute("prev-page-id", `${pagination_data.current_page}`)
        } else {
            prevPageButton.setAttribute("prev-page-id", `${pagination_data.current_page - 1}`)
        }

        nextPageButton.setAttribute("next-page-id", `${pagination_data.current_page + 1}`);

        const pageInfoSpan = document.getElementById('pageInfo');

        /* translators: 1: start index, 2: ending index, 3: total users */
        pageInfoSpan.textContent = sprintf(
            __('Showing %1$s to %2$s of %3$s users', 'author-kit'),
            pagination_data.start_index,
            pagination_data.ending_index,
            pagination_data.total_users
        );


        // Sorting ************************************************************************* //

        const tableHead = document.querySelector("#profileTable thead");
        tableHead.setAttribute("current-page-id", `${pagination_data.current_page}`);

        // *************************************************************************************** //


    }
    finally {
        // Get the loader element
        const loader = document.getElementById("loader");

        // hide the loader after forming table
        loader.style.display = "none";
    }

}


// Function to handle switch box functionality
function switch_boxes_functionality() {
    const bioWidgetSwitches = document.querySelectorAll('.bio-widget-switch');
    const displayAllBioWidget = document.getElementById('display-all-bio-widget');

    // Bulk "Display All" Bio Widget switch
    if (is_edit_users) {
        displayAllBioWidget.addEventListener('change', function () {
            const shouldEnable = this.checked;
            let updates = {};

            bioWidgetSwitches.forEach(switchElem => {
                if (selectedIds.includes(switchElem.dataset.userId)) {
                    switchElem.checked = shouldEnable; // Sync UI
                    updates[switchElem.dataset.userId] = { 'author_kit_bio_widget': shouldEnable };
                }
            });

            if (Object.keys(updates).length > 0) {
                update_meta_value_batch(updates);
            }
        });
    }


    // Individual Bio Widget switch change
    bioWidgetSwitches.forEach(switchElem => {
        switchElem.addEventListener('change', function () {
            let updates = { [this.dataset.userId]: { 'author_kit_bio_widget': this.checked } };
            update_meta_value_batch(updates);

            // Sync "Display All" Bio Widget
            syncDisplayAllState(bioWidgetSwitches, displayAllBioWidget);
        });
    });

}

function syncDisplayAllState(switches, displayAllElem) {
    const selectedSwitches = Array.from(switches).filter(elem => selectedIds.includes(elem.dataset.userId));

    if (selectedSwitches.length === 0) {
        displayAllElem.checked = false;
        displayAllElem.indeterminate = false;
        return;
    }

    const allChecked = selectedSwitches.every(elem => elem.checked);
    const someChecked = selectedSwitches.some(elem => elem.checked);

    displayAllElem.checked = allChecked;
    displayAllElem.indeterminate = !allChecked && someChecked; // Show mixed state
}



// Function to batch update meta values
function update_meta_value_batch(updates) {
    if (!updates || Object.keys(updates).length === 0) return;

    fetch(author_kit_profile_table_vars.ajax_url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        body: new URLSearchParams({
            'action': 'author_kit_update_user_meta',
            'updates': JSON.stringify(updates),
            'nonce': author_kit_profile_table_vars.nonce
        })
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // show_author_kit_toast('Data updated for users' , 'success');
            } else {
                show_author_kit_toast(__('Error in Updating User Data', 'author-kit'), 'error');
            }
        })
        .catch(error => show_author_kit_toast(__('Failed to Update User Data', 'author-kit'), 'error'));
}

function initialize_sorting() {
    const sortableHeaders = document.querySelectorAll(".sortable");

    // Default sorting based on global variables
    sortableHeaders.forEach(header => {
        const column = header.getAttribute("data-column");
        const sortIcons = header.querySelector(".sort-icons");
        const ascIcon = sortIcons.querySelector(".asc");
        const descIcon = sortIcons.querySelector(".desc");

        if (column === orderBy) {
            if (orderDirection === "ASC") {
                ascIcon.classList.add("active");
                descIcon.classList.remove("active");
            } else if (orderDirection === "DESC") {
                descIcon.classList.add("active");
                ascIcon.classList.remove("active");
            }
        } else {
            ascIcon.classList.remove("active");
            descIcon.classList.remove("active");
        }
    });

    // Add event listeners for sorting
    sortableHeaders.forEach(header => {
        const sortIcons = header.querySelector(".sort-icons");
        const ascIcon = sortIcons.querySelector(".asc");
        const descIcon = sortIcons.querySelector(".desc");
        const column = header.getAttribute("data-column");

        sortIcons.addEventListener("click", () => {
            // Determine current state and toggle between ASC and DESC
            if (orderBy === column && orderDirection === "ASC") {
                orderDirection = "DESC"; // Switch to descending
            } else {
                orderDirection = "ASC"; // Default to ascending
                orderBy = column; // Update to the selected column
            }

            // Reset all icons
            sortableHeaders.forEach(h => {
                const otherSortIcons = h.querySelector(".sort-icons");
                otherSortIcons.querySelector(".asc").classList.remove("active");
                otherSortIcons.querySelector(".desc").classList.remove("active");
            });

            // Activate the appropriate icon for the selected column
            if (orderDirection === "ASC") {
                ascIcon.classList.add("active");
                descIcon.classList.remove("active");
            } else {
                descIcon.classList.add("active");
                ascIcon.classList.remove("active");
            }

            // Reload the table with updated sorting
            const tableHead = document.querySelector("#profileTable thead");
            current_page_ID = tableHead.getAttribute("current-page-id");

            fetch_data(current_page_ID);
        });
    });
}

function on_change_option() {
    const rowsPerPageSelect = document.getElementById('rowsPerPage');

    // Add an event listener for the 'change' event
    rowsPerPageSelect.addEventListener('change', function () {
        // Get the selected value
        userPerPage = this.value;
        fetch_data(1);

    });
}

function on_click_next() {
    nextPageBtn = document.getElementById("nextPage");
    nextPageBtn.addEventListener('click', function () {

        nextPageId = nextPageBtn.getAttribute("next-page-id");
        fetch_data(nextPageId);

    });
}

function on_click_previous() {
    prevPageBtn = document.getElementById("prevPage");
    prevPageBtn.addEventListener('click', function () {

        prevPageId = prevPageBtn.getAttribute("prev-page-id");
        fetch_data(prevPageId);
    })
}


// Select All functionality for the table
function select_boxes_functionality() {
    const selectAllCheckbox = document.getElementById('select-all');
    const rowCheckboxes = document.querySelectorAll('.row-checkbox');
    const switchContainer = document.getElementById('switch-container');

    // Select All functionality
    selectAllCheckbox.addEventListener('change', function () {
        let selectAllIds = [];

        rowCheckboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
            if (this.checked) {
                selectAllIds.push(checkbox.value);
            }
        });

        selectedIds = selectAllIds;

        // Toggle visibility of switch-container
        toggleSwitchContainerVisibility();

        // Sync Display All switches
        syncDisplayAllState(document.querySelectorAll('.bio-widget-switch'), document.getElementById('display-all-bio-widget'));
    });

    // Row checkbox functionality
    rowCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function () {
            const checkboxId = this.value;

            if (this.checked) {
                if (!selectedIds.includes(checkboxId)) {
                    selectedIds.push(checkboxId);
                }
            } else {
                selectedIds = selectedIds.filter(id => id !== checkboxId);
            }

            selectAllCheckbox.checked = selectedIds.length === rowCheckboxes.length;

            // Toggle visibility of switch-container
            toggleSwitchContainerVisibility();

            // Sync Display All switches
            syncDisplayAllState(document.querySelectorAll('.bio-widget-switch'), document.getElementById('display-all-bio-widget'));
        });
    });
}

// Function to show/hide switch-container
function toggleSwitchContainerVisibility() {
    const switchContainer = document.getElementById('switch-container');
    switchContainer.style.display = selectedIds.length > 0 ? 'block' : 'none';
}


function author_profile_filter_active_tab() {
    const filterTabs = document.getElementById('filter-tabs');

    if (!filterTabs) {
        show_author_kit_toast(__('Filter Tabs Not Found', 'author-kit'), 'error');
        return;
    }

    function handleTabClick(event) {
        // Remove active styles from all tabs
        filterTabs.querySelectorAll('p').forEach(element => {
            element.style.color = 'black';
            element.style.fontWeight = 'normal';
        });

        // Add active styles to the clicked tab
        event.target.style.color = '#4e6fe7';
        event.target.style.fontWeight = 'bolder';
    }

    // Attach click event dynamically for all tabs
    filterTabs.addEventListener('click', function (event) {
        if (event.target.tagName === 'P') {
            handleTabClick(event);
        }
    });

    // Set the first tab as active by default after roles are loaded
    const observer = new MutationObserver(() => {
        const firstTab = filterTabs.querySelector('p');
        if (firstTab) {
            handleTabClick({ target: firstTab });
            observer.disconnect();
        }
    });

    observer.observe(filterTabs, { childList: true });
}
