let tableHeadings = ["Sr.No", "Image", "Is black and white?", "Category", "Keywords", "Credits", "Approval Action"];
let editFlag = false;
let checkFlag = 0;
let initialiseDataTable = true;

$(document).ready(function () {
    scrollToTopHandler();
    createTable(database);
    showDataTable();
});

// Function to handle scroll to top functionality
function scrollToTopHandler() {
    $(window).scroll(function () {
        if ($(this).scrollTop() > 50) {
            $('#back-to-top').fadeIn();
        } else {
            $('#back-to-top').fadeOut();
        }
    });

    $('#back-to-top').click(function () {
        $('body,html').animate({ scrollTop: 0 }, 400);
        return false;
    });
}

// Function to create the table structure
function createTable(imageData) {
    let thead = $('<thead>');
    let tr = $('<tr>');
    tableHeadings.forEach((heading, index) => {
        $('<th>').prop('id', 'tableHead' + (index + 1)).text(heading).appendTo(tr);
    });
    thead.append(tr);
    $("#dataTable").append(thead);
    let tbody = $('<tbody>').prop('id', 'tableData');
    $("#dataTable").append(tbody);
    createTBody(imageData);
}

// Function to initialize or refresh DataTable
function showDataTable() {
    if ($.fn.DataTable.isDataTable('#dataTable')) {
        $('#dataTable').DataTable().destroy();
    }
    $('#dataTable').removeAttr('width').DataTable({
        "autoWidth": false,
        "ordering": false,
        'columnDefs': [
            { orderable: false, targets: [1, 2, 4, 5, 6] }
        ]
    });
    $('.dataTableDiv').show();
}

// Function to create the table body dynamically
function createTBody(imageData) {
    let tbody = $('#tableData');
    imageData.forEach((data, i) => {
        let tr = $('<tr>').data("rowData", i).data("id", data.id);
        let keywords = data.keyword.endsWith(",") ? data.keyword.slice(0, -1) : data.keyword;
        let elements = [
            $('<td>').text(i + 1),
            $('<td>').html(`<img data-toggle="modal" data-target="#myModal" data="${data.url}" onclick="showModal(this)" class="img-responsive imgThumbnail noPadding" src="${data.thumb_url}">`),
            $('<td>').html(`<input type="checkbox" class="checkbox" onclick="is_grey_clicked(this)" style="cursor:pointer" ${data.is_grey === 'True' ? 'checked' : ''}>`),
            $('<td>').html(`<h6 style="cursor:pointer" onclick="edit_category_clicked(this);">${data.category}</h6>`),
            $('<td>').html(`<h6 style="cursor:pointer" onclick="edit_keywords_clicked(this);">${keywords}</h6>`),
            $('<td>').html(`<h6 style="cursor:pointer" onclick="edit_credits_clicked(this);">${data.credits}</h6>`),
            $('<td>').html('<div style="display:inline-flex"><button class="button btn_delete" onclick="delete_resource(this)">Delete</button></div>')
        ];
        elements.forEach(el => tr.append(el));
        tbody.append(tr);
    });
}

// Checkbox click handler for "Is black and white?"
function is_grey_clicked(ele) {
    checkFlag = $(ele).prop("checked") ? 1 : 0;
    postData(mark_resource_color_link, {
        status: checkFlag,
        id: $(ele).closest('tr').data('id')
    });
}

// Function to save the edited category
function save_category(ele, category) {
    let new_category = ($(ele).prev().val()).trim();
    if (category !== new_category && new_category !== '') {
        postData(save_category_link, {
            category,
            new_category,
            id: $(ele).closest('tr').data('id')
        }, (response) => {
            response = JSON.parse(response);
            $(ele).parent().prev().text(response['msg']['category_list']);
            $(ele).parent().prev().parent().next().find('h6').text(response['msg']['keyword_list']);
            $(ele).parent().hide();
            $(ele).parent().prev().show();
            $(ele).parent().remove();
        });
    } else {
        resetCategoryInput(ele);
    }
}

// Generic function to reset the input fields
function resetCategoryInput(ele) {
    $(ele).parent().hide();
    $(ele).parent().prev().show();
    $(ele).parent().remove();
}

// Generic function to post data using AJAX
function postData(url, data, successCallback = null) {
    data.csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val();
    $.ajax({
        type: 'POST',
        url,
        data,
        success: function (response) {
            if (successCallback) successCallback(response);
        },
        error: function () {
            alert('Error');
        }
    });
}

// Modal handler
function showModal(ele) {
    $('#modalImage').prop('src', $(ele).attr('data'));
}

// Function to delete resource
function delete_resource(ele) {
    postData(deletion_link, {
        id: $(ele).closest('tr').data('id')
    }, (response) => {
        response = JSON.parse(response);
        if (response['msg'] === 'deleted') {
            $(ele).closest('tr').remove();
        } else {
            alert(response['msg']);
        }
    });
}
