// rowCells = [group_key, answers_key, answers, view]
let rowCells = [];

// selectedGroupCells = [group_key, answers_key, answers]
let selectedGroupCells = [];
const $frmSearchSurveyCards = $('#frmSearchSurveyCards');

function selectCardBySurveyID(el) {
    rowCells = $(el).parent().parent().children();

    $('#selected-survey').text(`${rowCells[1].innerText}: ${rowCells[2].innerText}`);

    selectedGroupCells[0] = rowCells[0].innerText;
    selectedGroupCells[1] = rowCells[1].innerText;
    selectedGroupCells[2] = rowCells[2].innerText;

    getAvailableAndAssignedSurveyCards();
    $frmSearchSurveyCards.find('input').val('');

}

$('#card-cat').change(function () {
    getAvailableAndAssignedSurveyCards();
})

$(function () {
    $frmSearchSurveyCards.submit(function (e) {
        e.preventDefault();
        const form = $(this);
        const search = form.find('input').val();
        getAvailableAndAssignedSurveyCards(search);
    });
});

function getAvailableAndAssignedSurveyCards(search) {
    search = search || '';
    $('#selected-survey-wrapper').show();
    $('#loading-message').show();
    $('#card-tables-wrapper').hide();

    let param = {
        answersKey: selectedGroupCells[1],
        cardCat: $('#card-cat').val(),
        search: search,
    }

    $.ajax({
        method: 'post',
        url: '/feed/getAvailableAndAssignedSurveyCards',
        dataType: 'json',
        data: param
    })
        .done(function (data) {
            $('#loading-message').hide();
            $('#card-tables-wrapper').show();

            let availableCards = data.result.availableCards;
            let assignedCards = data.result.assignedCards;

            createAvailableCardsTable(availableCards);
            createAssignedCardsTable(assignedCards);
        })
        .fail(function (err) {
            $('#loading-message').hide();
            $('#card-tables-wrapper').show();
            console.log(err);
        });
}

function createAvailableCardsTable(result) {
    $('#available-cards tbody').empty();

    if (result.length === 0) {
        let tr = "<tr><td>empty</td><td>empty</td></tr>";
        $('#available-cards tbody').append(tr);
        return;
    }

    for (index in result) {
        var id = result[index].id;
        var name = result[index].name;
        var title = result[index].title;

        var tr = "<tr>";
        tr += `<td>${name}<br><strong>${id}</strong> - ${title}</td>`;
        tr += `<td><button type="button" class="btn btn-primary" onclick="assignCard(${id})">+</button></td>`;
        tr += "</tr>";

        $('#available-cards tbody').append(tr);
    }
}

function createAssignedCardsTable(result) {
    $('#assigned-cards tbody').empty();

    if (result.length === 0) {
        let tr = "<tr><td>empty</td><td>empty</td></tr>"
        $('#assigned-cards tbody').append(tr);
        return;
    }

    for (let index in result) {
        const id = result[index].id;
        const name = result[index].name;
        const title = result[index].title;
        const added = result[index].added;

        let tr = "<tr style='cursor: pointer;'>";
        tr += `<td><button type="button" class="btn btn-danger" onclick="unassignCard(${id})">-</button></td>`;
        tr += `<td>${name}<br><strong>${id}</strong> - ${title}</td>`;
        tr += "</tr>";

        $('#assigned-cards tbody').append(tr);
    }
}

function assignCard(id) {
    let data = {id, answersKey: selectedGroupCells[1]};
    $.ajax({
        method: 'post',
        url: '/feed/assignSurveyCard',
        dataType: 'json',
        data: data
    })
        .done(function (res) {
            getAvailableAndAssignedSurveyCards();
        })
        .fail(function (err) {
            console.log(err);
        });
}

function unassignCard(id) {
    let data = {id, answersKey: selectedGroupCells[1]};
    $.ajax({
        method: 'post',
        url: '/feed/unassignSurveyCard',
        dataType: 'json',
        data: data
    })
        .done(function (res) {
            getAvailableAndAssignedSurveyCards();
        })
        .fail(function (err) {
            console.log(err);
        });
}

$('#survey_filter_btn').click(function () {
    filterSurvey();
})

function filterSurvey() {
    $('#survey-loading-message').show();
    $('#survey-table').hide();

    let data = {
        groupKey: $('#groupKey').val(),
        answersKey: $('#answersKey').val(),
        answers: $('#answers').val()
    };

    $.ajax({
        method: 'post',
        url: '/feed/getOnboardingSurvey',
        dataType: 'json',
        data: data
    })
        .done(function (res) {
            createSurveyTable(res.data.result);
            renderPagination(res.data.total, res.data.pageSize);
            $('#survey-loading-message').hide();
            $('#survey-table').show();
        })
        .fail(function (err) {
            $('#survey-loading-message').hide();
            $('#survey-table').show();

            let errors = Object.values(err.responseJSON.errors);
            let message = '';
            for (index in errors) {
                message += errors[index];
            }
            alert(message);
        });
}

function createSurveyTable(result) {
    $('#survey-table tbody').empty();

    if (result.length === 0) {
        let tr = "<tr><td>empty</td><td>empty</td><td>empty</td><td>empty</td></tr>"
        $('#survey-table tbody').append(tr);
        return;
    }

    for (let index in result) {
        const id = result[index].id;
        const group_key = result[index].group_key;
        const answers_key = result[index].answers_key;
        const answers = result[index].answers;

        let tr = "<tr>";
        tr += `<td>${group_key}</td>`;
        tr += `<td>${answers_key}</td>`;
        tr += `<td data-id="${id}" contenteditable="true">${answers}</td>`;
        tr += `<td><button type="button" class="btn btn-primary show-cards" onclick="selectCardBySurveyID(this)">Cards</button></td>`;
        tr += "</tr>";

        $('#survey-table tbody').append(tr);
    }

    bindContenteditableEvent();
}

// handle edit answers column
let selectedSurveyID = 0;
let newAnswers = '';
let oldAnswers = '';

$('#update-answers-btn').click(function () {
    let data = {
        id: selectedSurveyID,
        answers: newAnswers
    }

    $.ajax({
        method: 'post',
        url: '/feed/updateSurveyAnswers',
        dataType: 'json',
        data: data
    })
        .done(function (res) {
            $('#edit-btn-wrapper').hide();
            alert(res.message);
        })
        .fail(function (err) {
            $('#edit-btn-wrapper').hide();

            let errors = Object.values(err.responseJSON.errors);
            let message = '';

            for (index in errors) {
                message += errors[index];
            }

            alert(message);
        });
});

$(document).ready(function () {
    bindContenteditableEvent();
})

function bindContenteditableEvent() {
    $('#discard-change-btn').click(function () {
        $(`td[data-id='${selectedSurveyID}']`).text(oldAnswers);
        $('#edit-btn-wrapper').hide();
    });

    const $contenteditable = $('td[contenteditable="true"]');
    $contenteditable.on('input', function (e) {
        showAnswersControl(e);
        newAnswers = e.target.innerText;
    });

    $contenteditable.focus(function (e) {
        showAnswersControl(e);
        selectedSurveyID = e.target.getAttribute('data-id');
        newAnswers = e.target.innerText;
        oldAnswers = e.target.innerText;
    });
}

// if user click anywhere outside the answers content then hide the answers control
window.onclick = function (e) {
    if (!e.target.hasAttribute('data-id') && e.target.id !== 'edit-btn-wrapper' && !e.target.classList.contains('edit-btn')) {
        $('#edit-btn-wrapper').hide();
    }
}

function showAnswersControl(e) {
    // 15 = padding top 15px
    // 116 = 15px (padding right) + 101px (View column header width)
    let topPosition = 15 + $('#search-form').height() + e.target.offsetTop;

    $('#edit-btn-wrapper').css('cssText', `
        display: block;
        top: ${topPosition}px;
        right: 116px;
    `);
}

// handle pagination

function renderPagination(total, pageSize) {
    $('#survey-pagination').empty();
    $('#survey-pagination').unbind('page');
    $('#survey-pagination').bootpag({
        total: Math.ceil(total / pageSize),
        page: 1,
        maxVisible: 5,
        leaps: true,
        firstLastUse: true,
        first: '←',
        last: '→',
        wrapClass: 'pagination',
        activeClass: 'active',
        disabledClass: 'disabled',
        nextClass: 'next',
        prevClass: 'prev',
        lastClass: 'last',
        firstClass: 'first'
    }).on("page", function(event, pageNo) {
        getSurvey(pageNo);
    });
}

function getSurvey(pageNo) {
    $('#survey-loading-message').show();
    $('#survey-table').hide();

    let data = {
        groupKey: $('#groupKey').val(),
        answersKey: $('#answersKey').val(),
        answers: $('#answers').val(),
        pageNo
    };

    $.ajax({
        method: 'post',
        url: '/feed/getOnboardingSurvey',
        dataType: 'json',
        data: data
    })
        .done(function (res) {
            createSurveyTable(res.data.result);
            $('#survey-loading-message').hide();
            $('#survey-table').show();
        })
        .fail(function (err) {
            $('#survey-loading-message').hide();
            $('#survey-table').show();

            let errors = Object.values(err.responseJSON.errors);
            let message = '';
            for (index in errors) {
                message += errors[index];
            }
            alert(message);
        });
}
