jQuery.expr[':'].icontains = function(a, i, m) {
    return jQuery(a).text().toUpperCase()
        .indexOf(m[3].toUpperCase()) >= 0;
};

$(document).ready(() => {

    // Enable all tooltips on the page
    const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]')
    const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl))

    teamsLoading(true);  // show the loading icon
    fetchAndLoadTeams(); // load the teams


    // Search functionality
    var searchTimeout = null;

    $("#search").keyup(() => {
        clearTimeout(searchTimeout);
        teamsLoading(true);

        searchTimeout = setTimeout(() => {
            fetchAndLoadTeams(...getFilters());
        }, 500)
    });

    $("#searchButton").on("click", () => {
        fetchAndLoadTeams(...getFilters());
    });

    $("#sortForm input").on("click", function() {
        const name = $(this).attr("name");
        localStorage.setItem(name, $(`input[name='${name}']:checked`, "#sortForm").val());7

        fetchAndLoadTeams(...getFilters());
    });

    const sortTeamsValue = localStorage.getItem("sortTeams");
    if (sortTeamsValue !== null) {
        $("#sortForm input[name='sortTeams']").val([sortTeamsValue]);
    }

    const sortMembersValue = localStorage.getItem("sortMembers");
    if (sortMembersValue !== null) {
        $("#sortForm input[name='sortMembers']").val([sortMembersValue]);
    }

    // Edit member form validation options
    $("#editMemberForm").validate({
        errorClass: "text-danger mb-2"
    })

    // Prevent dropdowns from closing when clicking inside
    $('.dropdown-menu').on('hide.bs.dropdown', function (e) {
        var target = $(e.clickEvent.target);
        if(target.hasClass("keepopen") || target.parents(".keepopen").length){
            return false; // returning false should stop the dropdown from hiding.
        }else{
            return true;
        }
    });
});

function getFilters() {
    return [
        $("#search").val(),
        $("input[name='sortTeams']:checked", "#sortForm").val(),
        $("input[name='sortMembers']:checked", "#sortForm").val()
    ]
}

/**
 * Returns bool if the string is empty or only contains whitespace
 * 
 * **/
function isEmptyOrSpaces(string) {
    return string === null || string.match(/^ *$/) !== null;
}

function loadTeams(teams, highlightText="") {
    $("#teamsContainer").html("");  // Clear the previous listed teams

    if (teams.length < 1) {
        $("#teamsNotFound").show();
    }

    // Iterate over and add each team
    teams.forEach((team) => {
        $("#teamsContainer").append(
            `<div class='col-12 col-md-6 col-xl-4 mb-4'>
                <div
                    class='team px-4 py-3 bg-body-secondary bg-gradient rounded h-100 fluid-hover-zoom shadow-sm shadow-on-hover'
                    data-number='${team.team_number}' 
                    data-section='${team.section_letter}'>
                    <h3>
                        <span class='fs-4'>
                            <span class='fs-6'>TEAM</span> 
                            ${team.team_number}
                        </span>
                        <span class='fs-5 text-secondary'>
                            <span class='fs-6'>SECTION</span>
                            ${team.section_letter}
                        </span>
                        <button class='btn btn-sm btn-outline-secondary float-end border-0 me-1'>
                            <i class='bi bi-gear fs-6'></i>
                        </button>
                    </h3>
                    <ul class='list-unstyled team-members mt-3'>
                    </ul>
                </div>
            </div>`
        );

        // Whilimage.pnge we have the team, iterate over and add it's members
        team.members.forEach((member) => {
            const fullname = member.first + " " + member.last;

            $("#teamsContainer").find(".team-members").last().append(
                `<li class='bg-body-tertiary mb-3 rounded w-100'>
                    <div 
                        class='team-member d-flex'
                        data-first='${member.first}'
                        data-last='${member.last}'
                        data-member-id='${member.id}'
                        data-team-number='${member.team}'
                        data-peg-number='${member.peg}'>
                        <div class='px-3 py-2'>
                            <span class='text-secondary me-2'>
                                ${member.peg}
                            </span>
                            <span class='team-member-fullname'>
                                ${fullname}
                            </span>
                        </div>
                        <button type='button' class='ms-auto btn btn-outline-secondary border-0 btn-sm fs-6 m-1' style="max-height: 32px;">
                            <i class='bi bi-pencil'></i>
                        </button>
                    </div>
                </li>`
            );
        });
    });

    // Highlight all instances where the text matches the search critera
    if (!isEmptyOrSpaces(highlightText)) {
        $("#teamsContainer").find('.team-member-fullname').each(function() {
            var regex = new RegExp(highlightText, 'gi');
            $(this).html($(this).text().replace(regex, '<span class="text-primary fw-bold">$&</span>'));
        });
    }
    
    // Bind edit team modal to the edit team button
    $(".team > h3 > button").on("click", function() {
        openEditTeamModal($(this).parent().parent().data("number"));
    });

    // Bind edit member modal to the edit member button
    $(".team-member button").on("click", function() {
        $(this).addClass("active");
        $("#editMemberModal").off("hidden.bs.modal").on("hidden.bs.modal", function() {
            $("#teamsContainer").find(".team").find("button.active").removeClass("active");
        });
        openEditMemberModal($(this).parent().data("member-id"));
    });
}

function fetchAndLoadTeams(search="", sortTeams="", sortMembers="") {
    $.ajax({
        url: getTeamsUrl,
        type: "post",
        data: {
            "csrfmiddlewaretoken": csrfMiddlewareToken,
            "search": !isEmptyOrSpaces(search) ? search : null,  // might not be necessary? TODO: re-evaluate
            "sortTeams": sortTeams ? sortTeams : null,
            "sortMembers": sortMembers ? sortMembers : null
        },
        error: (xhr, textStatus, errorThrown) => { alert(errorThrown); },
        success: (result) => {
            teamsLoading(false);
            loadTeams(result.teams, search);
        }
    });
}

function teamsLoading(show=true) {
    $("#teamsNotFound").hide()

    if (show) {
        $("#teamsContainer").hide();
        $("#teamsLoadingSpinner").show();
        return
    }

    $("#teamsContainer").show();
    $("#teamsLoadingSpinner").hide();
}

function openEditTeamModal(teamNumber) {

    // Team data
    const team = $(`.team[data-number='${teamNumber}']`);
    const section = team.data("section");

    // Load data to form
    $("#editTeamTitle").text(`Team ${teamNumber}`);

    $("#editTeamNumber").val(teamNumber);
    $('#editTeamSection').val(section);

    $("#editTeamModal").modal("show");
}

function openEditMemberModal(memberId) {

    // Member data
    const member = $(`.team-member[data-member-id='${memberId}']`);
    const first = member.data("first");
    const last = member.data("last");
    const teamNumber = member.data("team-number");
    const pegNumber = member.data("peg-number");

    // Load teams as options
    $("#editMemberTeam").html("");
    $(".team").map(function() {
        return $(this).data("number");
    }).get().forEach((team) => {
        $("#editMemberTeam").append($(`<option value='${team}'>Team ${team}</option>`));
    });

    // Load data to form
    $("#editMemberName").text(first + " " + last);
    $("#editMemberFirstName").val(first);
    $("#editMemberLastName").val(last);
    $("#editMemberTeam").val(teamNumber);
    $("#editMemberPeg").val(pegNumber);

    $("#editMemberFirstName").attr("placeholder", first);
    $("#editMemberLastName").attr("placeholder", last);

    $("#editMemberModal").modal("show");

    // Update the submit button
    $("#saveEditModal").off("click").on("click", () => { saveEditMemberModal(memberId); });
}

function saveEditMemberModal(memberId) {

    if (!$("#editMemberForm").valid()) {
        return;
    }

    // Grab the updated data
    const first = $("#editMemberFirstName").val();
    const last = $("#editMemberLastName").val();
    const teamNumber = $("#editMemberTeam").val();
    const pegNumber = $("#editMemberPeg").val();
    const search = $("#search").val();

    teamsLoading(true);

    $.ajax({
        url: updateMemberUrl,
        type: "post",
        data: {
            "csrfmiddlewaretoken": csrfMiddlewareToken,
            "memberId": memberId,
            "first": first,
            "last": last,
            "teamNumber": teamNumber,
            "pegNumber": pegNumber,
            "search": !isEmptyOrSpaces(search) ? search : null
        },
        error: (xhr, textStatus, errorThrown) => { alert(errorThrown); },
        success: (result) => {
            teamsLoading(false);
            loadTeams(result.teams, search);
            $("#editMemberModal").modal("hide");
        }
    });
}