const CONSTANTS = {
    GRID: '#caseParticipants',
    SUBJECT_TYPES: {
        CUSTOMER: '#SubjectTypeCustomer',
        WITNESS: '#SubjectTypeWitness',
        EXPERT: '#SubjectTypeExpert',
        OPPOSITE: '#SubjectTypeOppositeParty',
        REPRESENTATIVE: '#SubjectTypeRepresentative'
    },
    MODALS: {
        SHARE_COSTS: '#editShareOfCostsModal',
        ERROR: 'caseParticipantErrorModal',
        DELETE: 'deleteParticipantModal'
    },
    INPUTS: {
        SHARE: '#shareOfCosts',
        PARTICIPANT_ID: '#participantId',
        SUBJECT: '#Subject',
        SUBJ_TYPE: '#SubjType'
    },
    URLS: {
        ADD_PARTICIPANT: '#AddCaseParticipantUrl',
        DELETE_PARTICIPANT: '#DeleteCaseParticipantUrl',
        UPDATE_SHARE: '#UpdateParticipantShareOfCostsUrl',
        LIST_PARTICIPANTS: '#CaseParticipantsListUrl'
    }
};

function getSubjectTypeText(type) {
    const typeMap = {
        [$(CONSTANTS.SUBJECT_TYPES.WITNESS).val()]: $('#WitnessLoc').val(),
        [$(CONSTANTS.SUBJECT_TYPES.EXPERT).val()]: $('#ExpertLoc').val(),
        [$(CONSTANTS.SUBJECT_TYPES.CUSTOMER).val()]: $('#CustomerLoc').val(),
        [$(CONSTANTS.SUBJECT_TYPES.OPPOSITE).val()]: $('#OppositePartyLoc').val(),
        [$(CONSTANTS.SUBJECT_TYPES.REPRESENTATIVE).val()]: $('#RepresentativeLoc').val()
    };
    return typeMap[type] || type || '';
}

function refreshCaseParticipantsGrid() {
    const table = $(CONSTANTS.GRID).DataTable();
    const lastId = table.data().length ? table.data()[0].Id : null;

    table.ajax.reload(function () {
        const newData = table.data();
        if (newData.length && (!lastId || newData[0].Id > lastId)) {
            const $newRow = $(`tr[data-qid="${newData[0].Id}"]`);
            $newRow.addClass("table-hover");
        }
    }, false);
}

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

function openShareOfCostsModal(qId, currentShare, subjType) {
    qId = parseInt(qId, 10);

    if (isNaN(qId) || qId <= 0) {
        caseParticipantError($('#GeneralErrorMessageLoc').val());
        return;
    }

    if (subjType !== $(CONSTANTS.SUBJECT_TYPES.CUSTOMER).val()) {
        return;
    }

    $(CONSTANTS.INPUTS.PARTICIPANT_ID).val(qId);
    $(CONSTANTS.INPUTS.SHARE).val(currentShare || 0);
    $(CONSTANTS.MODALS.SHARE_COSTS).modal('show');
}

function calculateTotalShare(currentParticipantId) {
    let total = 0;
    const table = $(CONSTANTS.GRID).DataTable();

    table.rows().every(function () {
        const data = this.data();
        if (data.SubjType === $(CONSTANTS.SUBJECT_TYPES.CUSTOMER).val() &&
            parseInt(data.Id) !== parseInt(currentParticipantId)) {
            total += parseFloat(data.ShareOfCosts || 0);
        }
    });

    return total;
}

function saveShareOfCosts() {
    const qId = parseInt($(CONSTANTS.INPUTS.PARTICIPANT_ID).val(), 10);
    const shareOfCosts = parseFloat($(CONSTANTS.INPUTS.SHARE).val());

    if (isNaN(qId) || qId <= 0) {
        caseParticipantError($('#GeneralErrorMessageLoc').val());
        return;
    }

    if (isNaN(shareOfCosts) || shareOfCosts < 0 || shareOfCosts > 100) {
        caseParticipantError($('#InvalidShareValueLoc').val());
        return;
    }

    const totalShare = calculateTotalShare(qId);
    if ((totalShare + shareOfCosts) > 100) {
        caseParticipantError($('#TotalShareExceeds100Loc').val());
        return;
    }

    $('#saveShareOfCostsBtn').prop('disabled', true);

    $.ajax({
        url: $(CONSTANTS.URLS.UPDATE_SHARE).val(),
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ qId, shareOfCosts }),
        success: function (response) {
            if (response.success) {
                $(CONSTANTS.MODALS.SHARE_COSTS).modal('hide');
                refreshCaseParticipantsGrid();
            } else {
                caseParticipantError(response.message || $('#GeneralErrorMessageLoc').val());
            }
        },
        error: function () {
            caseParticipantError($('#GeneralErrorMessageLoc').val());
        },
        complete: function () {
            $('#saveShareOfCostsBtn').prop('disabled', false);
        }
    });
}

function deleteParticipant(qId) {
    qId = parseInt(qId, 10);

    if (isNaN(qId)) {
        caseParticipantError($('#GeneralErrorMessageLoc').val());
        return;
    }

    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        id: CONSTANTS.MODALS.DELETE,
        type: "alert",
        text: $('#DeleteParticipantConfirmLoc').val(),
        buttons: [
            {
                icon: 'fa fa-check',
                text: $("#ConfirmLoc").val(),
                closeOnAction: true,
                type: 'primary',
                action: function () {
                    $.ajax({
                        url: $(CONSTANTS.URLS.DELETE_PARTICIPANT).val(),
                        type: 'POST',
                        data: { qId },
                        traditional: true,
                        success: function (response) {
                            if (response.success) {
                                refreshCaseParticipantsGrid();
                            } else {
                                caseParticipantError($('#DeleteParticipantErrorLoc').val());
                            }
                        },
                        error: function () {
                            caseParticipantError($('#GeneralErrorMessageLoc').val());
                        }
                    });
                }
            },
            {
                icon: 'fa fa-times',
                text: $("#CancelDeleteLOC").val(),
                closeOnAction: true,
                type: 'link'
            }
        ]
    });
}

function addParticipant() {
    const subject = $(CONSTANTS.INPUTS.SUBJECT).val();
    const subjectType = $(CONSTANTS.INPUTS.SUBJ_TYPE).val();
    const caseNumber = $('#CaseNumber').val();

    if (!subject || !subjectType) {
        caseParticipantError($('#RequiredFieldsMessageLoc').val());
        return;
    }

    $.ajax({
        url: $(CONSTANTS.URLS.ADD_PARTICIPANT).val(),
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ caseNumber, subject, subjectType }),
        success: function (response) {
            if (response.success) {
                $(CONSTANTS.INPUTS.SUBJECT).val('').trigger('change');
                $(CONSTANTS.INPUTS.SUBJ_TYPE).val('').trigger('change');
                refreshCaseParticipantsGrid();
            } else {
                caseParticipantError($('#GeneralErrorMessageLoc').val());
            }
        },
        error: function () {
            caseParticipantError($('#GeneralErrorMessageLoc').val());
        }
    });
}

function initializeCaseParticipantsGrid() {
    const $grid = $(CONSTANTS.GRID);
    const caseNumber = $('#CaseNumber').val();;

    if (!$grid.length) return;

    if ($.fn.DataTable.isDataTable(CONSTANTS.GRID)) {
        $grid.DataTable().destroy();
    }

    $grid.DataTable({
        processing: true,
        serverSide: false,
        responsive: true,
        ajax: {
            url: $(CONSTANTS.URLS.LIST_PARTICIPANTS).val(),
            type: 'POST',
            data: function (d) {
                return { caseNumber };
            },
            dataSrc: function (response) {
                return (response.data || []).sort((a, b) => b.Id - a.Id);
            }
        },
        columns: [
            { data: 'Subject', render: data => data || '' },
            { data: 'Address', render: data => data || '' },
            { data: 'SubjType', render: data => getSubjectTypeText(data) || '' },
            {
                data: 'ShareOfCosts',
                render: (data, type, row) => {
                    const isCustomer = row.SubjType === $(CONSTANTS.SUBJECT_TYPES.CUSTOMER).val();
                    if (!isCustomer) return '-';

                    const shareValue = data ? `${data}%` : '0%';
                    if (!row.Id) return shareValue;

                    return `<a href="#" class="share-of-costs-value" 
                        data-toggle="tooltip" 
                        data-placement="right" 
                        data-qid="${row.Id}" 
                        data-share="${data || 0}" 
                        data-type="${row.SubjType}" 
                        title="${$('#EditShareOfCostsLoc').val()}">${shareValue}</a>`;
                }
            },
            {
                data: null,
                orderable: false,
                render: (data, type, row) => {
                    const isWitnessOrExpert = [
                        $(CONSTANTS.SUBJECT_TYPES.WITNESS).val(),
                        $(CONSTANTS.SUBJECT_TYPES.EXPERT).val()
                    ].includes(row.SubjType);

                    return isWitnessOrExpert ?
                        `<button class="btn btn-danger btn-sm delete-participant" data-qid="${row.Id}">
                            <i class="fas fa-trash"></i>
                        </button>` : '';
                }
            }
        ],
        createdRow: function (row, data) {
            $(row).attr('data-qid', data.Id);
        },
        order: [],
        language: {
            emptyTable: $('#NoParticipantsLoc').val(),
            processing: $('#LoadingLoc').val(),
            search: "",
            lengthMenu: "_MENU_",
            info: "",
            infoEmpty: "",
            zeroRecords: $('#NoParticipantsLoc').val(),
            paginate: {
                first: "<<",
                previous: "<",
                next: ">",
                last: ">>"
            }
        },
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50]],
        pageLength: 10
    });
}

$(document).ready(function () {
    initializeCaseParticipantsGrid();

    $('#NewParticipant').on('click', function (e) {
        e.preventDefault();
        addParticipant();
    });

    $(document).on('mouseover', '.share-of-costs-value', function () {
        $(this).tooltip();
    });

    $(document).on('click', '.share-of-costs-value', function (e) {
        e.preventDefault();
        const $element = $(this);
        openShareOfCostsModal(
            parseInt($element.data('qid'), 10),
            parseFloat($element.data('share')) || 0,
            $element.data('type')
        );
    });

    $(document).on('click', '.delete-participant', function (e) {
        e.preventDefault();
        deleteParticipant($(this).data('qid'));
    });

    $(CONSTANTS.MODALS.SHARE_COSTS).on('shown.bs.modal', function () {
        $(CONSTANTS.INPUTS.SHARE).focus();
    });

    $(CONSTANTS.MODALS.SHARE_COSTS).on('hidden.bs.modal', function () {
        $(CONSTANTS.INPUTS.SHARE).val('');
        $(CONSTANTS.INPUTS.PARTICIPANT_ID).val('');
    });

    $('#saveShareOfCostsBtn').on('click', function (e) {
        e.preventDefault();
        saveShareOfCosts();
    });
});