const createReceiptLoc = $("#CreateReceiptLOC").val();
const createInvoiceFromSelectedLoc = $("#CreateInvoiceFromSelectedLOC").val();
const createInvoiceGetUrl = $("#PerformedTasksCreateInvoiceUrl").val();
let selectedEventItems = [];

$(document).ready(() => {
    initializeComponents();
    bindEvents();
    updateActionButton();
    initializeParticipantPricesAndCosts();
    markInvoicedTasks();
    initializeScrollBehavior();
});

function parseLocaleNumber(stringNumber) {
    if (!stringNumber) return 0;

    if (typeof stringNumber === 'number') return stringNumber;

    const cleanedStr = stringNumber.toString().replace(/[^\d.,]/g, '');

    const lastCommaIndex = cleanedStr.lastIndexOf(',');
    const lastDotIndex = cleanedStr.lastIndexOf('.');

    let processedStr = cleanedStr;

    if (lastCommaIndex > lastDotIndex) {
        processedStr = cleanedStr.replace(/\./g, '').replace(',', '.');
    } else if (lastDotIndex > lastCommaIndex && lastCommaIndex !== -1) {
        processedStr = cleanedStr.replace(/,/g, '');
    }

    const result = parseFloat(processedStr);
    return isNaN(result) ? 0 : result;
}

function initializeComponents() {
    $(".custom-checkbox").customCheckbox();
    $('.datepicker').datepicker({
        format: 'dd.mm.yyyy',
        autoclose: true,
        todayHighlight: true
    });
}

function bindEvents() {
    $(document).on('change', '.task-checkbox', function () {
        updateActionButton();
        updateSelectedTasks(this);
    });
}

function updateActionButton() {
    $('#createInvoiceButton').prop('disabled', !$('.task-checkbox:checked').length);
}

function submitPerformedTasksFilterForm() {
    $("#performed-tasks-filter-form").submit();

    $(document).ajaxComplete(function (event, xhr, settings) {
        if (settings.url.includes("PerformedTasksList")) {
            setTimeout(function () {
                $(".custom-checkbox").customCheckbox();
                markInvoicedTasks();
            }, 100);
        }
    });
}

function updateSelectedTasks(checkbox) {
    const eventId = parseInt(checkbox.value);
    const itemInput = $(`#item-${eventId}`);
    const itemValue = $(`#item-value-${eventId}`);
    const globalDoctype = $('#global-doctype');

    if (checkbox.checked) {
        selectedEventItems.push({
            performedTaskId: eventId,
            selectedDocType: {
                docType: globalDoctype.val(),
                name: globalDoctype.find("option:selected").text()
            },
            selectedItem: {
                ident: itemValue.val(),
                name: itemInput.val(),
            }
        });
    } else {
        selectedEventItems = selectedEventItems.filter(item => item.performedTaskId !== eventId);
    }
}

function updateSelectedTaskItem(taskId) {
    const itemValue = $(`#item-value-${taskId}`);
    const itemIdent = itemValue.val();
    const itemName = itemValue.data('name');
    const itemPrice = parseLocaleNumber(itemValue.data('price')) || 0;

    const existingItem = selectedEventItems.find(item => item.performedTaskId === taskId);

    if (existingItem) {
        existingItem.selectedItem = {
            ident: itemIdent,
            name: itemName,
        };
    }

    setParticipantPricesAndCosts(taskId);
    updateCreateInvoiceButtonsState(taskId);
}

function markInvoicedTasks() {
    if (typeof window.chronosItems === 'undefined' || !Array.isArray(window.chronosItems)) {
        return;
    }

    const processTaskRows = () => {
        $('#performedTasksTbl tbody tr[id^="performed-task-row-"]').each(function () {
            const $row = $(this);
            const taskId = parseInt($row.attr('id').replace('performed-task-row-', ''));

            if (isNaN(taskId)) return;

            const $participantsRows = $(`#participants-body-${taskId} tr[data-task-id="${taskId}"]`);
            const hasInvoicedItems = window.chronosItems.some(item => item && item.PerformedTaskChronosItemId === taskId);
            const allParticipantsInvoiced = $participantsRows.length > 0 &&
                $participantsRows.length === $participantsRows.filter('.invoiced-row').length;

            if (hasInvoicedItems && allParticipantsInvoiced) {
                disableTaskControls($row, true);
            }

            const $validParticipants = $participantsRows.filter(function () {
                const $participant = $(this);
                const shareOfCosts = parseLocaleNumber($participant.data('share-of-costs')) || 0;
                const isInvoiced = $participant.hasClass('invoiced-row');

                return shareOfCosts > 0 && !isInvoiced;
            });

            if ($participantsRows.length > 0 && $validParticipants.length === 0) {
                disableTaskControls($row, true);
            }

            const hasNoValidParticipants = $(`#participants-body-${taskId}`).find('tr[data-participant-id]').length === 0 ||
                $(`#participants-body-${taskId}`).find('td.text-center:contains("' + $("#NoPerformedTasksLoc").val() + '")').length > 0;

            if (hasNoValidParticipants) {
                disableTaskControls($row, false);
            }
        });
    };

    const processParticipantRows = () => {
        $('tr[data-participant-id]').each(function () {
            const $row = $(this);
            const taskId = parseInt($row.data('task-id'));
            const participantId = parseInt($row.data('participant-id'));
            const shareOfCosts = parseLocaleNumber($row.data('share-of-costs'));

            if (isNaN(taskId) || isNaN(participantId)) return;

            const isInvoiced = window.chronosItems.some(item =>
                item && item.PerformedTaskChronosItemId === taskId && item.ParticipantId === participantId);

            if (isInvoiced) {
                $row.addClass('invoiced-row');
                $row.find('input, select, button').prop('disabled', true);
                $row.find('button').hide();

                const $checkbox = $row.find('input[type="checkbox"]');
                $checkbox.prop('checked', true);

                const $customCheckbox = $checkbox.next('.custom-checkbox-checkmark');
                if ($customCheckbox.length) {
                    $customCheckbox.addClass('checked').css('background-color', '#28a745');
                }
            }

            if (shareOfCosts === 0) {
                $row.addClass('text-muted');
                $row.find('input, select, .discount, .note').prop('disabled', true);

                const $checkbox = $row.find('input[type="checkbox"]');
                $checkbox.addClass('hidden-checkbox');

                const $customCheckbox = $checkbox.next('.custom-checkbox-checkmark');
                if ($customCheckbox.length) {
                    $customCheckbox
                        .attr('style', `
                            display: flex !important;
                            justify-content: flex-start !important;
                            font-weight: bolder !important;
                            color: white !important;
                            background-color: #dc3545 !important;
                            font-size: 12px !important;
                            overflow: hidden !important;
                        `)
                        .removeClass('checked')
                        .html('<span class="x-mark" style="position: absolute !important; top: 0 !important; left: 0 !important; right: 0 !important; bottom: 0 !important; display: flex !important; justify-content: center !important; align-items: center !important; font-weight: 900 !important; font-size: 14px !important; text-shadow: 0px 0px 1px #fff !important; color: white !important;">&#10005;</span>');
                }
            }
        });
    };

    processTaskRows();
    processParticipantRows();
}

function disableTaskControls($row, isInvoiced) {
    if (isInvoiced) {
        $row.addClass('table-success');

        const $selectCheckbox = $row.find('.task-checkbox');
        $selectCheckbox.prop('disabled', true);
        $selectCheckbox.closest('td').addClass('text-muted');

        const $lastCheckbox = $row.find('input[type="checkbox"]:last');
        $lastCheckbox.prop('checked', true);

        const $lastCheckboxSpan = $lastCheckbox.next('.custom-checkbox-checkmark');
        if ($lastCheckboxSpan.length) {
            $lastCheckboxSpan.addClass('checked').css('background-color', '#28a745');
        }
    } else {
        $row.addClass('no-participants');
    }

    const $noteInput = $row.find('.note-input');
    $noteInput.prop('readonly', true);
    $noteInput.addClass('bg-light text-muted');
}

function showAlert(message) {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "alert",
        text: message,
        buttons: [{
            icon: 'fa fa-check',
            text: $("#ConfirmLoc").val(),
            closeOnAction: true,
            type: 'primary'
        }]
    });
}

function openCreateInvoice() {
    const button = $(event.target).closest('button');
    const buttonId = button.attr('id');

    if (buttonId && buttonId.startsWith('createInvoiceButton-')) {
        const idParts = buttonId.replace('createInvoiceButton-', '').split('-');

        if (idParts.length === 2) {
            const participantId = parseInt(idParts[0]);
            const taskId = parseInt(idParts[1]);

            const participantRow = $(`tr[data-participant-id="${participantId}"][data-task-id="${taskId}"]`);
            const taskRow = $(`#performed-task-row-${taskId}`);

            const itemValue = $(`#item-value-${taskId}`);
            const itemField = $(`#item-${taskId}`);
            const itemId = itemValue.val();
            const itemName = itemField.val();
            const itemPrice = parseLocaleNumber(itemValue.data('price')) || 0;

            const doctypeValue = $(`#doctype-value-${taskId}`);
            const doctypeField = $(`#doctype-${taskId}`);
            const doctypeId = doctypeValue.val();
            const doctypeName = doctypeField.val();

            const note = $(`#note-${taskId}`).val();

            const taskTime = parseLocaleNumber(taskRow.data('time')) || 0;
            const shareOfCosts = parseLocaleNumber(participantRow.data('share-of-costs')) || 0;

            const originalCost = (taskTime * itemPrice * shareOfCosts) / 100;

            $('#modal-participant-id').val(participantId);
            $('#modal-task-id').val(taskId);
            $('#modal-item-id').val(itemId);
            $('#modal-doctype-id').val(doctypeId);
            $('#modal-time').text(taskTime.toString());
            $('#modal-share-of-costs').text(shareOfCosts.toString() + ' %');
            $('#modal-price').text(itemPrice.toFixed(2));
            $('#modal-cost').text(originalCost.toFixed(2));
            $('#modal-discount').val(0);
            $('#modal-note').val(note);

            $('#modal-task-time').data('time', taskTime);
            $('#modal-cost').data('original-cost', originalCost);

            const $itemSelect = $('#modal-item-select');
            $itemSelect.val(itemId);
            $itemSelect.selectpicker('refresh');

            const $doctypeSelect = $('#modal-doctype-select');
            $doctypeSelect.val(doctypeId);
            $doctypeSelect.selectpicker('refresh');

            $('#modal-discount').off('input').on('input', updateModalCost);

            if ($('#add-invoice-modal').length > 0) {
                $('#add-invoice-modal').modal('show');
            } else {
                createInvoiceForParticipant(taskId, participantId, button);
            }
        }
    } else {
        const selectedCheckboxes = $('.task-checkbox:checked');
        if (selectedCheckboxes.length > 0) {
            createInvoiceForSelectedTasks();
        }
    }
}

function updateGlobalDocType(element) {
    const $element = $(element);
    const docTypeData = {
        DocType: $element.val(),
        Name: $element.find("option:selected").text()
    };

    $('.task-checkbox:checked').each(function () {
        const eventId = parseInt(this.value);
        const existingItem = selectedEventItems.find(item => item.performedTaskId === eventId);
        if (existingItem) {
            existingItem.selectedDocType = docTypeData;
        }
    });
}

function updateNote(element, taskId) {
    const noteValue = $(element).val();
    const updateUrl = $("#UpdatePerformedTaskNoteUrl").val();

    $.ajax({
        url: updateUrl,
        type: 'POST',
        data: { id: taskId, note: noteValue },
        success: function (response) {
            if (response.success) {
                $(element).removeClass('is-invalid')
                    .addClass('border-success')
                    .delay(1000)
                    .queue(function () {
                        $(this).removeClass('border-success').dequeue();
                    });
            } else {
                $(element).addClass('is-invalid');
                showAlert($("#GeneralErrorMessageLoc").val());
            }
        },
        error: function () {
            $(element).addClass('is-invalid');
            showAlert($("#GeneralErrorMessageLoc").val());
        }
    });
}

function toggleParticipants(taskId) {
    const participantsRow = $(`#participants-row-${taskId}`);
    const expandButton = $(`.expand-participants-btn[data-task-id="${taskId}"]`);
    const isVisible = participantsRow.is(':visible');

    participantsRow.toggle(!isVisible);
    expandButton.find('i').toggleClass('fa-chevron-down fa-chevron-up');

    if (!isVisible) {
        participantsRow.find('.datepicker').datepicker({
            format: 'dd.mm.yyyy',
            autoclose: true,
            todayHighlight: true
        });

        setParticipantPricesAndCosts(taskId);
        updateCreateInvoiceButtonsState(taskId);
    }
}

function updateCreateInvoiceButtonsState(taskId) {
    $(`#participants-body-${taskId} button[id^="createInvoiceButton-"]`).each(function () {
        const $button = $(this);
        $button.prop('disabled', false);
        $button.attr('title', '');

        const itemValue = $(`#item-value-${taskId}`);
        const itemId = itemValue.val();
        const hasItem = itemId && itemId !== "";

        if (!hasItem) {
            $button.attr('title', $("#ItemSelectLoc").val());
        }
    });
}

function setParticipantPricesAndCosts(taskId) {
    const itemValue = $(`#item-value-${taskId}`);
    const itemIdent = itemValue.val();
    const taskRow = $(`#performed-task-row-${taskId}`);
    const taskTime = parseLocaleNumber(taskRow.data('time')) || 0;

    let itemPrice = 0;

    if (itemIdent && itemIdent !== '') {
        itemPrice = parseLocaleNumber(itemValue.data('price')) || 0;
    }

    $(`tr[data-task-id="${taskId}"]`).each(function () {
        const participantRow = $(this);
        const participantId = parseInt(participantRow.data('participant-id'));
        const shareOfCosts = parseLocaleNumber(participantRow.data('share-of-costs'));

        const isInvoiced = window.chronosItems && window.chronosItems.some(item =>
            item &&
            item.PerformedTaskChronosItemId === taskId &&
            item.ParticipantId === participantId
        );

        if (!isInvoiced) {
            participantRow.find('.item-price').text(itemPrice.toFixed(2));

            let cost = 0;
            if (!isNaN(shareOfCosts)) {
                cost = (taskTime * itemPrice * shareOfCosts) / 100;

                const discount = parseLocaleNumber(participantRow.find('.discount').val()) || 0;
                if (discount > 0 && discount <= 100) {
                    cost = cost * (1 - (discount / 100));
                }
            }

            participantRow.find('.cost').text(cost.toFixed(2));
        }
    });
}

function createInvoiceForParticipant(taskId, participantId, button) {
    const participantRow = $(`tr[data-participant-id="${participantId}"][data-task-id="${taskId}"]`);
    const shareOfCosts = parseLocaleNumber(participantRow.data('share-of-costs'));
    const docDate = participantRow.find('.doc-date').val();
    const vatDate = participantRow.find('.vat-date').val();
    const discount = $('#modal-discount').val() || participantRow.find('.discount').val();
    const note = $('#modal-note').val() || participantRow.find('.note').val();

    const participantName = participantRow.find('td:first').text();
    const participantAddress = participantRow.data('address') || '';

    const createInvoiceUrl = $("#PerformedTasksCreateInvoiceUrl").val();

    const itemSelect = $('#modal-item-select');
    const docTypeSelect = $('#modal-doctype-select');

    const itemIdent = itemSelect.val() || $('#modal-item-id').val() || $(`#item-value-${taskId}`).val();
    const docTypeId = docTypeSelect.val() || $('#modal-doctype-id').val() || $(`#doctype-value-${taskId}`).val();

    let docType = '';
    if (docTypeSelect.val()) {
        const selectedOption = docTypeSelect.find("option:selected");
        docType = selectedOption.text();
    } else {
        docType = $('#modal-doctype').text() || $(`#doctype-${taskId}`).val();
    }

    let itemPrice = 0;
    if (itemSelect.val()) {
        const selectedOption = itemSelect.find("option:selected");
        itemPrice = parseLocaleNumber(selectedOption.data("price")) || 0;
    } else {
        itemPrice = parseLocaleNumber($('#modal-price').text()) || 0;
    }

    const formattedDiscount = discount ? parseLocaleNumber(discount).toString() : '0';
    const formattedShareOfCosts = shareOfCosts.toString();
    const formattedItemPrice = itemPrice.toString();

    const taskRow = $(`#performed-task-row-${taskId}`);
    const caseFromTask = taskRow.data('case') || '';

    const params = new URLSearchParams();
    params.append('selectedPerformedTasks[0].PerformedTaskId', taskId);
    params.append('selectedPerformedTasks[0].SelectedItemId', itemIdent);
    params.append('selectedPerformedTasks[0].CaseNumber', caseFromTask);
    params.append('selectedPerformedTasks[0].ParticipantId', participantId);
    params.append('selectedPerformedTasks[0].DocDate', docDate);
    params.append('selectedPerformedTasks[0].VatDate', vatDate);
    params.append('selectedPerformedTasks[0].Discount', formattedDiscount);
    params.append('selectedPerformedTasks[0].Note', note);
    params.append('selectedPerformedTasks[0].ShareOfCosts', formattedShareOfCosts);
    params.append('selectedPerformedTasks[0].ItemPrice', formattedItemPrice);
    params.append('selectedPerformedTasks[0].ReceiverId', participantId);
    params.append('selectedPerformedTasks[0].ReceiverName', participantName);
    params.append('selectedPerformedTasks[0].ReceiverAddress', participantAddress);

    const docTypeName = docType.split(' (')[0] || docType;

    params.append('selectedDocType.DocType', docTypeId);
    params.append('selectedDocType.Name', docTypeName);

    $(button).prop('disabled', true).html(`<i class="fa fa-spinner fa-spin"></i> ${$("#LoadingLoc").val()}`);

    window.location.href = `${createInvoiceUrl}?${params.toString()}`;
}

function updateTaskDocType() {
    return;
}

function getItemPrice(taskId) {
    const itemValue = $(`#item-value-${taskId}`);
    const itemIdent = itemValue.val();

    if (!itemIdent || itemIdent === '') {
        return 0;
    }

    const price = itemValue.data('price');
    const itemPrice = parseLocaleNumber(price);
    return (itemPrice > 0) ? itemPrice : 0;
}

function initializeParticipantPricesAndCosts() {
    $('#performedTasksTbl tbody tr[id^="performed-task-row-"]').each(function () {
        const rowId = $(this).attr('id');
        const taskId = parseInt(rowId.replace('performed-task-row-', ''));
        setParticipantPricesAndCosts(taskId);
    });
}

function updateModalCost() {
    const taskTime = parseLocaleNumber($('#modal-task-time').data('time')) || 0;
    const shareOfCosts = parseLocaleNumber($('#modal-share-of-costs').text()) || 0;
    const itemPrice = parseLocaleNumber($('#modal-price').text()) || 0;
    const discount = parseLocaleNumber($('#modal-discount').val()) || 0;

    const baseCost = (taskTime * itemPrice * shareOfCosts) / 100;

    if (discount >= 0 && discount <= 100) {
        const discountedCost = baseCost * (1 - (discount / 100));
        $('#modal-cost').text(discountedCost.toFixed(2));
    }
}

$(document).ready(function () {
    $('#modal-create-invoice-button').on('click', function () {
        const itemSelect = $('#modal-item-select');
        if (!itemSelect.val()) {
            showAlert($("#ItemSelectLoc").val());
            return;
        }

        const docTypeSelect = $('#modal-doctype-select');
        if (!docTypeSelect.val()) {
            showAlert($("#DocumentTypeSelectLoc").val());
            return;
        }

        $('#add-invoice-modal').modal('hide');

        const participantId = parseInt($('#modal-participant-id').val());
        const taskId = parseInt($('#modal-task-id').val());
        const discount = $('#modal-discount').val();
        const note = $('#modal-note').val();

        const participantRow = $(`tr[data-participant-id="${participantId}"][data-task-id="${taskId}"]`);
        if (participantRow.length > 0) {
            if (participantRow.find('.discount').length > 0) {
                participantRow.find('.discount').val(discount);
            }
            if (participantRow.find('.note').length > 0) {
                participantRow.find('.note').val(note);
            }
        }

        createInvoiceForParticipant(taskId, participantId, $(`#createInvoiceButton-${participantId}-${taskId}`));
    });

    $('#modal-discount').on('input', updateModalCost);

    $('.selectpicker').selectpicker({
        noneSelectedText: $("#SelectLoc").val(),
        liveSearch: true,
        size: 7
    });
});

function updateModalItemSelection(element) {
    const $element = $(element);
    const selectedOption = $element.find("option:selected");

    $('#modal-item-id').val($element.val());

    const itemPrice = parseLocaleNumber(selectedOption.data("price")) || 0;
    $('#modal-price').text(itemPrice.toFixed(2));

    updateModalCost();
}

function updateModalDocTypeSelection(element) {
    const $element = $(element);

    $('#modal-doctype-id').val($element.val());
}

function initializeScrollBehavior() {
    $('.performed-tasks-table-wrapper').css({
        'height': 'clamp(300px, 70vh, 90vh)',
        'overflow-y': 'auto',
        'position': 'relative'
    });

    $('.calendar-list-container').css({
        'position': 'relative',
        'width': '100%',
        'margin-top': '20px',
        'height': 'calc(100vh - 150px)',
        'overflow-y': 'auto',
        'min-height': '200px',
        'border': '1px solid rgb(192, 192, 192)'
    });

    $(window).on('resize', function() {
        adjustScrollHeights();
    });
}

function adjustScrollHeights() {
    const windowHeight = $(window).height();
    
    $('.performed-tasks-table-wrapper').css({
        'height': `clamp(300px, ${windowHeight * 0.7}px, ${windowHeight * 0.9}px)`
    });

    $('.calendar-list-container').css({
        'height': `calc(${windowHeight}px - 150px)`
    });
}