const subcasesTableId = 'subcases';
const casesTableId = 'cases';
const SCROLL_OFFSET = 150;

let selectedCases = [];
const dateFormat = $("#DateFormatLOC").val().toUpperCase();

function initializeCases(tableId) {
    const columns = [
        {
            data: function (data) {
                return data.CostDrv;
            },
            orderable: false,
            className: 'dt-body-center',
            render: function (data) {
                data = data.replace("value=", "");
                return `<input name="casesSelection" class="checkbox-active" type="checkbox" onclick="checkBoxClicked(this.value)" value="${data}" />`;
            }
        },
        { data: "CostDrvView", name: "CaseNumber", filtertype: "text", render: $.fn.dataTable.render.link("CostDrv") },
        { data: "CostDrvTmAdditionalFields.RefNum", name: "InternalNumber", filtertype: "text" },
        {
            data: null,
            name: "Customer",
            filtertype: "text",
            render: function (data, type, row) {
                if (row.CostDrvTmCustomers.length) {
                    return row.CostDrvTmCustomers.map(customer => `<a href="${$('#EditSubjectURL').val()}?id=${customer}">${customer}</a>`).join(', ');
                }

                return "";
            }
        },
        {
            data: null,
            name: "OppositeParty",
            filtertype: "text",
            render: function (data, type, row) {
                if (row.CostDrvTmOppositeParties) {
                    return row.CostDrvTmOppositeParties.map(oppositeParty => `<a href="${$('#EditSubjectURL').val()}?id=${oppositeParty}">${oppositeParty}</a>`).join(', ');
                }

                return "";
            }
        },
        {
            data: null,
            name: "Representative",
            filtertype: "text",
            render: function (data, type, row) {
                if (row.CostDrvTmRepresentatives) {
                    return row.CostDrvTmRepresentatives.map(representative => `<a href="${$('#EditSubjectURL').val()}?id=${representative}">${representative}</a>`).join(', ');
                }

                return "";
            }
        },
        {
            data: "CostDrvTmAdditionalFields.DisputeValue",
            name: "DisputeValue",
            filtertype: "text",
            render: function (data) {
                const number = parseFloat(data);
                return isNaN(number) ? 0 : number.toFixed(2)
            }
        },
        {
            data: "CostDrvTmAdditionalFields.Court", name: "CompetentCourt", filtertype: "text", render: function (data) {
                const court = data || "";
                return court.length > 20 ? court.substring(0, 20) + "..." : court;
            }
        },
        {
            data: "DateStart",
            name: "OpenDate",
            filtertype: "text",
            className: 'dt-body-center',
            render: function (data) {
                return moment(data).format(dateFormat);
            }
        },
        {
            data: "DateEnd", name: "StatuteOfLimitations", filtertype: "text", render: function (data) {
                return data ? moment(data).format(dateFormat) : "";
            }
        },
        { data: "Name", name: "ShortCaseDescription", filtertype: "text" },
        {
            data: null,
            name: "Status",
            filtertype: "select",
            render: function (data, type, row) {
                let className = '';
                let statusName = row.StatusName;

                if (row.Status === $("#InProgress").val()) {
                    className = 'status-I';
                } else if (row.Status === $("#Finished").val()) {
                    className = 'status-N';
                }
                return `<span class="${className}">${statusName}</span>`;
            }
        },
    ];

    initializeCasesDataTables(tableId, 'Keywords', columns);
}

function initializeCasesDataTables(tableId, keywordsId, columns) {
    const url = new URL(window.location.href);
    const createdCostDrv = decodeURI(url.searchParams.get("costDrv"));
    const doneTypingInterval = 600;
    let typingTimer;

    if (keywordsId.length > 0) {
        $('#' + keywordsId).off('keyup');
        $('#' + keywordsId).on('keyup', function () {
            clearTimeout(typingTimer);
            typingTimer = setTimeout(function () { reloadDataTable(tableId); }, doneTypingInterval);
        });
    }

    $('#Status, #Customer, #OppositeParty, #Representative, .custom-datepicker').change(function () {
        reloadDataTable(tableId);
    });

    if ($('#' + tableId).length !== 0) {
        $dataTable = $('#' + tableId);
        $dataTable.DataTable({
            ajax: {
                url: $dataTable.attr('data-url'),
                data: function (d) {
                    d.Keywords = $('#' + keywordsId).val();
                    d.Status = $("#Status").val();
                    d.CaseNumber = $("#CaseNumber").val();
                    d.Customer = $("#Customer").val();
                    d.OppositeParty = $("#OppositeParty").val();
                    d.Representative = $("#Representative").val();
                    d.DateFrom = $("#DateFrom").val();
                    d.DateTo = $("#DateTo").val();
                }
            },
            columns: columns,
            createdRow: function (row, data) {
                if (data.CostDrv == createdCostDrv) {
                    $(row).addClass('side-menu-item-active').children(":first").addClass('side-menu-item-active');
                }
            }
        });
    }
    $('#selectAll').on('change', function () {
        const checked = this.checked;
        $('input[name="casesSelection"]').each(function () {
            $(this).prop('checked', checked);

            if (checked && !selectedCases.includes($(this).val())) {
                selectedCases.push($(this).val());
            } else if (!checked) {
                const index = selectedCases.indexOf($(this).val());
                if (index > -1) {
                    selectedCases.splice(index, 1);
                }
            }
        });
        updateDeleteButtonState();
    });

}

function updateDeleteButtonState() {
    if (selectedCases.length > 0) {
        $('#deleteButton').removeClass('disabled');
    } else {
        $('#deleteButton').addClass('disabled');
    }
}

function checkBoxClicked(costDrv) {
    if (!selectedCases.includes(costDrv)) {
        selectedCases.push(costDrv);
    }
    else {
        const index = selectedCases.indexOf(costDrv);
        selectedCases.splice(index, 1);
    }

    updateDeleteButtonState()
}

function casesGridDelete(deleteUrl) {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: 'alert',
        text: selectedCases.length > 1 ? $("#DeleteCasesLOC").val() : $("#DeleteCaseLOC").val(),
        buttons: [
            {
                icon: 'fa fa-times',
                text: $("#CancelDeleteLOC").val(),
                closeOnAction: true,
                type: 'ghost'
            },
            {
                text: $("#ConfirmLoc").val(),
                closeOnAction: true,
                type: 'primary',
                action: function () {
                    deleteCases(deleteUrl)
                },
                icon: 'fa fa-check'
            }
        ]
    });
}

function updateNameField() {
    var value = $("#shortCaseDescription").val();
    $("#hiddenCaseDescription").val(value);
}

function checkIfCaseNumberExists() {
    if ($("#ActionMethod").val() === "Create") {       
        updateNameField();       
        $.ajax({
            type: 'GET',
            url: $("#CheckIfCaseNumberExistsUrl").val(),
            data: { caseNumber: $("#CostDrv").val() },
            success: function (response) {
                if (response.CaseNumberExists) {
                    casesErrorModal($("#CaseNumberAlreadyExistsLoc").val());
                } else {
                    $("#caseCreateForm").submit();
                }
            }
        });
    } else {
        updateNameField();
        
        $("#caseCreateForm").submit();
    }
}

function deleteCases(deleteUrl) {
    $.ajax({
        cache: false,
        type: "post",
        url: deleteUrl,
        data: {
            keys: selectedCases
        },
        success: function (response) {
            if (response.IsDeleteFailed) {
                let errorCasesMessage = '';

                if (response.ErrorCases && response.ErrorCases.length > 0) {
                    errorCasesMessage = `<p>${$("#AnErrorOccuredWhileDeletingCasesLoc").val()}:</p>`;
                    for (let i = 0; i < response.ErrorCases.length; i++) {
                        if (response.ErrorTables && response.ErrorTables.length > 0) {
                            errorCasesMessage += `<p>${response.ErrorCases[i]} - ${$("#CaseDeleteErrorLoc").val()}</p>`;
                        } else {
                            errorCasesMessage += `<p>${response.ErrorCases[i]}</p>`;
                        }
                    }
                }

                if (response.CasesWithSubcases && response.CasesWithSubcases.length > 0) {
                    const casesWithSubcases = generateCaseWithSubcasesMessage(response.CasesWithSubcases);
                    errorCasesMessage += `<p>${casesWithSubcases}</p>`;
                }

                casesErrorModal(errorCasesMessage);
                return;
            }

            selectedCases = [];
            $('#selectAll').prop('checked', false);
            $.fn.dataTable.reload($dataTable);
            $("#deleteButton").addClass('btn-outline disabled').removeClass('btn-danger');
        },
        error: function (error) {
            casesErrorModal($("#GeneralErrorMessage").val());
        }
    });
}

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

function generateCaseWithSubcasesMessage(list) {
    let output = "";
    for (let i = 0; i < list.length; i++) {
        output += `<p>${list[i]} ${$("#NotDeletedBecauseItHasSubcasesLoc").val()}</p>`;
    }
    return output;
}

function updateSelectedDropdownValue(selector, value) {
    if ($(selector).find(`option[value='${value}']`).length === 0) {
        $(selector).append(new Option(value, value, true, true)).trigger('change');
    } else {
        $(selector).val(value).trigger('change');
    }
}

$('#caseCreateForm').submit(function (event) {
    let isValid = true;

    updateNameField();
    
    const responsiblePerson = $('#ResponsiblePerson').val().trim();
    if (!responsiblePerson) {
        $('#ResponsiblePersonValidationError').text($("#ResponsiblePersonValidationErrorLOC").val());
        isValid = false;
    } else $('#ResponsiblePersonValidationError').text("")

    const customers = $('#CostDrvTmCustomers').val();
    if (!customers || customers.length === 0) {
        $('#CustomerValidationError').text($("#CustomerValidationErrorLOC").val());
        isValid = false;
    } else $('#CustomerValidationError').text("")

    if (!isValid) {
        event.preventDefault();
    }
});

$('#ResponsiblePerson').on('change', function () {
    $('#ResponsiblePersonValidationError').text("");
});

$('#CostDrvTmCustomers').on('change', function () {
    if ($(this).val().length > 0) {
        $('#CustomerValidationError').text("");
    }
});

$('#CostDrvTmOppositeParties').on('change', function () {
    if ($(this).val().length > 0) {
        $('#OppositePartyValidationError').text("");
    }
});

$('#OpenDate').on('change', function () {
    const [day, month, year] = $(this).val().split('.').map(Number);

    if (!day || !month || !year) return;

    const selectedDate = new Date(year, month - 1, day);
    const today = new Date().setHours(0, 0, 0, 0);
    const statusValue = selectedDate > today ? $("#Finished").val() : $("#InProgress").val();

    $('#status').val(statusValue).trigger('change');
});

$('#StatuteOfLimitations').on('change', function () {
    const [day, month, year] = $('#OpenDate').val().split('.').map(Number);
    if (!day || !month || !year) return;

    const startDate = new Date(year, month - 1, day);
    const today = new Date().setHours(0, 0, 0, 0);

    if (!$(this).val() && startDate <= today) {
        $('#status').val($("#InProgress").val()).trigger('change');
    }
});

function initializeScrollBehavior() {
    adjustScrollHeights();
    
    $('.mobile-scroll-wrapper').css({
        'height': `calc(100vh - ${SCROLL_OFFSET}px)`,
        'overflow-y': 'auto',
        'position': 'relative',
        'padding-right': '15px'
    });

    $('.modal-scroller .modal-content').css({
        'max-height': `calc(100vh - 60px)`,
        'overflow-y': 'auto'
    });

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

function adjustScrollHeights() {
    const windowHeight = $(window).height();
    const tabsOffset = $('.tabs-container').offset()?.top || 0;
    const buttonsHeight = $('.buttons-tabbed').outerHeight() || 0;
    const availableHeight = windowHeight - tabsOffset - buttonsHeight - 20;

    $('.mobile-scroll-wrapper').css({
        'height': `${availableHeight}px`
    });

    $('.modal-scroller .modal-content').css({
        'max-height': `${windowHeight - 60}px`
    });
}

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

