$("#btnGeneratePositions").on('click', function(e){
    e.preventDefault();
    let box_id = $(this).data('box_id');
    $.ajax({
        url: generate_positions_url,
        type: "POST",
        data: {
            "_token": csrf_token,
            box_id: box_id,
        },
        success: function(res){
            handleMessage(res.success, res.message)
            if(res.success){ setTimeout(function () {location.reload()}, messageDuration)}
        }
    });
});

let selectedPositionCard = null;

function setActionButtonsDefaultForOccupied()
{
    $("#btnRemoveAliquot").show();
    $("#btnShowMove").show();
    $("#btnShowHistory").show();
    $("#btnShowUseVolume").show();
    $("#btnBackActions").hide();
    $("#btnMoveAliquot").hide();
    $("#btnUseVolume").hide();
}

function openPositionModal(card)
{
    if (card === undefined || !card.length) {
        card = selectedPositionCard;
    }
    if (!card || !card.length) {
        return;
    }

    let modal = $("#modal-aliquot");
    let aliquotId = card.data('aliquot_id');

    modal.find('.modal-title').html('Storage Position ' + card.data('position_code'));
    modal.find('input[name="storage_position_id"]').val(card.data('position_id'));
    modal.find('input[name="aliquot_id"]').val(aliquotId || '');

    if (aliquotId) {
        $("#empty-form").hide();
        $("#btnSaveAliquot").hide();
        setActionButtonsDefaultForOccupied();
        $("#movement-panel").hide();
        $("#movement-history-panel").hide();
        $("#use-volume-panel").hide();
        $("#movement-history-body").html('');
        modal.find('.modal-body select[name="to_position_id"]').val("").trigger('change');
        modal.find('.modal-body textarea[name="movement_reason"]').val("");
        modal.find('.modal-body input[name="used_volume"]').val("");
        modal.find('.modal-body input[name="reference_number"]').val("");
        modal.find('.modal-body textarea[name="use_reason"]').val("");
        $("#current_remaining_volume").text((card.data('remaining_volume') || '0') + ' ' + (card.data('volume_unit') || ''));
        $("#occupied-summary").show().html(
            '<strong>Occupied:</strong> ' + (card.data('aliquot_number') || '') +
            '<br><strong>Sample:</strong> ' + (card.data('sample') || '-') +
            '<br><strong>Pathogen:</strong> ' + (card.data('pathogen') || '-') +
            '<br><strong>Remaining:</strong> ' + (card.data('remaining_volume') || '0') + ' ' + (card.data('volume_unit') || '') +
            '<br><strong>Status:</strong> ' + (card.data('status') || '-')
        );
    } else {
        $("#occupied-summary").hide().html('');
        $("#empty-form").show();
        $("#btnSaveAliquot").show();
        $("#btnRemoveAliquot").hide();
        $("#btnShowMove").hide();
        $("#btnShowHistory").hide();
        $("#btnShowUseVolume").hide();
        $("#btnBackActions").hide();
        $("#btnMoveAliquot").hide();
        $("#btnUseVolume").hide();
        $("#movement-panel").hide();
        $("#movement-history-panel").hide();
        $("#use-volume-panel").hide();
        $("#movement-history-body").html('');
        modal.find('.modal-body input[type="text"], .modal-body input[type="number"], .modal-body input[type="date"], .modal-body textarea').val("");
        modal.find('.modal-body select[name="sample_id"]').val("").trigger('change');
        modal.find('.modal-body select[name="pathogen_id"]').val("").trigger('change');
        modal.find('.modal-body select[name="container_type_id"]').val("").trigger('change');
        modal.find('.modal-body select[name="volume_unit"]').val("µL");
        modal.find('.modal-body select[name="status"]').val("Available");
    }

    modal.modal({backdrop: 'static'});
}

$(".position-card").on('click', function(){
    let card = $(this);
    selectedPositionCard = card;
    $(".position-card").removeClass("selected");
    card.addClass("selected");

    $("#selected_position_code").text(card.data('position_code') || '-');
    $("#selected_status").text(card.data('status') || 'Empty')
        .removeClass('badge-light badge-success badge-warning badge-danger')
        .addClass(card.data('aliquot_id') ? 'badge-success' : 'badge-light');
    $("#selected_tube").text(card.data('aliquot_number') || card.data('sample') || '-');
    $("#selected_pathogen").text(card.data('pathogen') || '-');
    let volume = card.data('remaining_volume') ? (card.data('remaining_volume') + ' ' + (card.data('volume_unit') || '')) : '-';
    $("#selected_volume").text(volume);
    $("#btnManageSelected").prop('disabled', false);
});

$(".position-card").on('dblclick', function(){
    selectedPositionCard = $(this);
    openPositionModal(selectedPositionCard);
});

$("#btnManageSelected").on('click', function(e){
    e.preventDefault();
    openPositionModal(selectedPositionCard);
});

$("#btnClearSelection").on('click', function(e){
    e.preventDefault();
    selectedPositionCard = null;
    $(".position-card").removeClass("selected");
    $("#selected_position_code").text('-');
    $("#selected_status").text('No selection').removeClass('badge-success badge-warning badge-danger').addClass('badge-light');
    $("#selected_tube").text('-');
    $("#selected_pathogen").text('-');
    $("#selected_volume").text('-');
    $("#btnManageSelected").prop('disabled', true);
});

$("#btnSaveAliquot").on('click', function(e){
    e.preventDefault();
    $.ajax({
        url: save_aliquot_url,
        type: "POST",
        data: {
            "_token": csrf_token,
            storage_position_id: $('#storage_position_id').val(),
            sample_id: $('#sample_id').val(),
            pathogen_id: $('#pathogen_id').val(),
            sample_code: $('#sample_code').val(),
            container_type_id: $('#container_type_id').val(),
            aliquot_number: $('#aliquot_number').val(),
            initial_volume: $('#initial_volume').val(),
            remaining_volume: $('#remaining_volume').val(),
            volume_unit: $('#volume_unit').val(),
            concentration: $('#concentration').val(),
            expiry_date: $('#expiry_date').val(),
            status: $('#status').val(),
            description: $('#description').val(),
        },
        success: function(res){
            handleMessage(res.success, res.message)
            if(res.success){ setTimeout(function () {location.reload()}, messageDuration)}
        }
    });
});

$("#btnShowMove").on('click', function(e){
    e.preventDefault();
    $("#movement-history-panel").hide();
    $("#use-volume-panel").hide();
    $("#btnUseVolume").hide();
    $("#btnShowMove").hide();
    $("#btnShowHistory").hide();
    $("#btnShowUseVolume").hide();
    $("#btnRemoveAliquot").hide();
    $("#btnBackActions").show();
    $("#movement-panel").show();
    $("#btnMoveAliquot").show();
});

$("#btnMoveAliquot").on('click', function(e){
    e.preventDefault();
    $.ajax({
        url: move_aliquot_url,
        type: "POST",
        data: {
            "_token": csrf_token,
            aliquot_id: $('#aliquot_id').val(),
            to_position_id: $('#to_position_id').val(),
            movement_reason: $('#movement_reason').val(),
        },
        success: function(res){
            handleMessage(res.success, res.message)
            if(res.success){ setTimeout(function () {location.reload()}, messageDuration)}
        }
    });
});

$("#btnShowHistory").on('click', function(e){
    e.preventDefault();
    $("#movement-panel").hide();
    $("#use-volume-panel").hide();
    $("#btnMoveAliquot").hide();
    $("#btnUseVolume").hide();
    $("#btnShowMove").hide();
    $("#btnShowHistory").hide();
    $("#btnShowUseVolume").hide();
    $("#btnRemoveAliquot").hide();
    $("#btnBackActions").show();
    $.ajax({
        url: movement_history_url,
        type: "POST",
        data: {
            "_token": csrf_token,
            aliquot_id: $('#aliquot_id').val(),
        },
        success: function(res){
            if(res.success) {
                let rows = '';
                if (res.data.length === 0) {
                    rows = '<tr><td colspan="5" class="text-center text-muted">No movement history found.</td></tr>';
                } else {
                    res.data.forEach(function(item){
                        rows += '<tr>' +
                            '<td>' + (item.moved_at || '-') + '</td>' +
                            '<td>' + (item.from || '-') + '</td>' +
                            '<td>' + (item.to || '-') + '</td>' +
                            '<td>' + (item.reason || '-') + '</td>' +
                            '<td>' + (item.moved_by || '-') + '</td>' +
                            '</tr>';
                    });
                }
                $("#movement-history-body").html(rows);
                $("#movement-history-panel").show();
            } else {
                handleMessage(res.success, res.message)
            }
        }
    });
});

$("#btnShowUseVolume").on('click', function(e){
    e.preventDefault();
    $("#movement-panel").hide();
    $("#movement-history-panel").hide();
    $("#btnMoveAliquot").hide();
    $("#btnShowMove").hide();
    $("#btnShowHistory").hide();
    $("#btnShowUseVolume").hide();
    $("#btnRemoveAliquot").hide();
    $("#btnBackActions").show();
    $("#use-volume-panel").show();
    $("#btnUseVolume").show();
});

$("#btnBackActions").on('click', function(e){
    e.preventDefault();
    $("#movement-panel").hide();
    $("#movement-history-panel").hide();
    $("#use-volume-panel").hide();
    $("#btnMoveAliquot").hide();
    $("#btnUseVolume").hide();
    $("#btnBackActions").hide();
    $("#btnRemoveAliquot").show();
    $("#btnShowMove").show();
    $("#btnShowHistory").show();
    $("#btnShowUseVolume").show();
});

$("#btnUseVolume").on('click', function(e){
    e.preventDefault();
    $.ajax({
        url: use_volume_url,
        type: "POST",
        data: {
            "_token": csrf_token,
            aliquot_id: $('#aliquot_id').val(),
            used_volume: $('#used_volume').val(),
            reference_number: $('#reference_number').val(),
            use_reason: $('#use_reason').val(),
        },
        success: function(res){
            handleMessage(res.success, res.message)
            if(res.success){ setTimeout(function () {location.reload()}, messageDuration)}
        }
    });
});

$("#btnRemoveAliquot").on('click', function(e){
    e.preventDefault();
    Swal.fire({
        text: 'Remove this aliquot from the storage position?',
        icon: 'question',
        showCancelButton: true,
        cancelButtonClass: 'danger',
        confirmButtonText: confirm_ok_delete,
        cancelButtonText: confirm_cancel
    }).then((result) => {
        if (result.value) {
            $.ajax({
                url: remove_aliquot_url,
                method: 'POST',
                data: {
                    "_token": csrf_token,
                    aliquot_id: $('#aliquot_id').val(),
                },
                success: function(res){
                    handleMessage(res.success, res.message)
                    if(res.success) { setTimeout(function () {location.reload()}, messageDuration) }
                }
            })
        }
    });
});
