const createAction = "create";
const updateAction = "update";
let action = '';

function toggleTrialPeriodEnd(trialPeriodCheckbox) {
    $(trialPeriodCheckbox).closest(".form-group").find("#TrialPeriodEndWrapper").toggleClass("hidden");
}

function handleJubilee(selectElement, itemId) {
    const type = $(selectElement).closest(".pm-accordion-container").find("#LOSType-" + itemId).val();
    const status = $(selectElement).closest(".pm-accordion-container").find("#Status-" + itemId).val();
    const jubilee = $(selectElement).closest(".pm-accordion-container").find("#IsJubilee-" + itemId);
    const jubileeValue = jubilee.val().toLowerCase();

    // If Work type is "InCompany" and Status is "Employment", Jubilee checkbox is on
    if (type == $("#WorkTypeInCompany").val()
        && status == $("#WorkStatusEmployment").val()
        && jubileeValue == "false") {
        jubilee.click();

    } else if ((type != $("#WorkTypeInCompany").val()
        || status != $("#WorkStatusEmployment").val())
        && jubileeValue == "true") {
        jubilee.click();
    }
}

function deleteWorkExperience(workId) {
    $.ajax({
        type: "DELETE",
        url: $("#DeleteWorkExperienceUrl").val(),
        data: {
            worker: $("#ModelWorker").val(),
            id: $("#WorkExperienceId-" + workId).val(),
        },
        success: function (data) {
            if (data.isDeleted) {
                $("#WorkExperienceId-" + workId).closest("div").remove();
                recalculateWorkBookChart();
            }
        }
    });
}

function parseDate(dateString) {
    const parts = dateString.split('.');
    if (parts.length === 3) {
        const day = parseInt(parts[0], 10);
        const month = parseInt(parts[1], 10) - 1;
        const year = parseInt(parts[2], 10);

        return new Date(year, month, day);
    }
    return null;
}

function checkIfChangedToCompany(element, previousId) {
    if ($(element).val() === $("#WorkTypeInCompany").val() && $(element).val() !== $("#" + previousId).val()) {
        $(element).addClass("hasChangedToCompany");
    }
    else {
        $(element).removeClass("hasChangedToCompany");
    }
}

function findLatestDateElement() {
    let latestDate = null;
    let latestElement = null;

    $('[id^="Begin-"]').not('#Begin-0').each(function () {
        const dateValue = $(this).val();
        const parsedDate = parseDate(dateValue);

        if (dateValue && parsedDate && !isNaN(parsedDate)) {
            if (!latestDate || parsedDate > latestDate) {
                latestDate = parsedDate;
                latestElement = this;
            }
        }
    });

    return { latestDate, latestElement };
}


function setWorkBookJobEntry(addJob, isTaxReduction = false) {
    if (action === createAction) {
        $("#AddJobPosition-0").val(addJob);
        setTaxReduction(0, isTaxReduction);
        addWorkExperienceAsync();
    }
    else {
        if (addJobUpdatePosition !== 0) {
            $("#AddJobPosition-" + addJobUpdatePosition).val(addJob);
            setTaxReduction(addJobUpdatePosition, isTaxReduction);
        }
        saveWorkBookDataAsync();
    }
}

function setTaxReduction(id, isTaxReduction) {
    if (isTaxReduction === true) {
        $("#AddTaxReduction-" + id).val(isTaxReduction);
    }
}

function addWorkExperience() {
    action = createAction;

    if ($("#LOSType-0").val() === $("#WorkTypeInCompany").val() && $("#Begin-0").val()) {
        toogleIrisEmploymentField(0);
        $('#workbook-job-iris').modal('show');
    }
    else {
        addWorkExperienceAsync();
    }
}

function addWorkExperienceAsync() {
    const newWorkExperience = getWorkExperienceData(0);

    $.ajax({
        type: "POST",
        url: $("#CreateWorkExperienceUrl").val(),
        data: newWorkExperience,
        success: function (data) {
            if (data) {
                handleNewRow(data);
                clearNewWorkExperienceFields();
                recalculateWorkBookChart();
                initializeDateTimePicker();
            }
        }
    });
}

let addJobUpdatePosition = 0;

function saveWorkBookData() {
    if ($(".hasChangedToCompany").length === 0) {
        saveWorkBookDataAsync();
        return;
    }
    action = updateAction;
    const { latestDate, latestElement } = findLatestDateElement();

    if (latestDate && latestElement) {
        const numberPart = $(latestElement).attr("id").split('-')[1];

        if ($("#LOSType-" + numberPart).hasClass("hasChangedToCompany")) {
            addJobUpdatePosition = numberPart;
            toogleIrisEmploymentField(numberPart);
            $('#workbook-job-iris').modal('show');
        } else {
            saveWorkBookDataAsync();
        }
    } else {
        saveWorkBookDataAsync();
    }
}

function saveWorkBookDataAsync() {
    const data = [];

    $(".isDirty").each(function () {
        const workId = $(this).attr("id").split("-")[1];
        if (workId === "new") {
            return true;
        }

        const workData = getWorkExperienceData(workId);
        data.push(workData);
    });

    if (data.length > 0) {
        $.ajax({
            type: "POST",
            url: $("#SaveWorkBookDataUrl").val(),
            contentType: "application/json",
            data: JSON.stringify(data),
            success: function (data) {
                if (data.Status) {
                    location.reload();
                } else {
                    showDefaultErrorCustomModal($("#GeneralErrorMessage").val(), $("#custom-modal-confirm").val());
                }
            },
            error: function () {
                showDefaultErrorCustomModal($("#GeneralErrorMessage").val(), $("#custom-modal-confirm").val());
            }
        });
    }
}

function getWorkExperienceData(itemId) {
    return {
        Worker: $("#ModelWorker").val(),
        Id: $("#WorkExperienceId-" + itemId).val(),
        QId: $("#WorkExperienceQId-" + itemId).val(),
        Begin: $("#Begin-" + itemId).val(),
        End: $("#End-" + itemId).val(),
        TrialPeriodEnd: $("#TrialPeriodEnd-" + itemId).val(),
        LOSType: $("#LOSType-" + itemId).val(),
        LOS: $("#LOS-" + itemId).val(),
        Note: $("#Note-" + itemId).val(),
        Status: $("#Status-" + itemId).val(),
        IsTrialPeriod: $("#IsTrialPeriod-" + itemId).val(),
        IsCounts: $("#IsCounts-" + itemId).val(),
        IsVacation: $("#IsVacation-" + itemId).val(),
        IsJubilee: $("#IsJubilee-" + itemId).val(),
        BeneLOS: $("#BeneLOS-" + itemId).val(),
        BeneLOSInc: $("#BeneLOSInc-" + itemId).val(),
        EntranceCause: $("#EntranceCause-" + itemId).val(),
        CeaseCause: $("#CeaseCause-" + itemId).val(),
        BeneLOSMonths: $("#BeneLOSMonths-" + itemId).val(),
        AddJobPosition: $("#AddJobPosition-" + itemId).val(),
        AddTaxReduction: $("#AddTaxReduction-" + itemId).val()
    }
}

function clearNewWorkExperienceFields() {
    $("#collapse-new-work").find("select").each(function () {
        $(this).val(null).trigger('change');
    });

    $("#collapse-new-work").find("input, textarea").each(function () {
        $(this).val('');
    });

    $("#collapse-new-work").find("#IsTrialPeriod-0, #IsJubilee-0").each(function () {
        $(this).prop("checked") && $(this).trigger("click");
    });

    $("#collapse-new-work").find("#IsCounts-0, #IsVacation-0").each(function () {
        !$(this).prop("checked") && $(this).trigger("click");
    });

    $("#OpenNewButton").removeClass("hidden");
    $("#AddNewButton").addClass("hidden");
}

$("#OpenWorkBook").on("click", function () {
    if ($(this).hasClass('disabled')) {
        return;
    }

    window.location.href = $("#EmployeeWorkBookUrl").val() + "?id=" + $("#ModelWorker").val();
});

function changeBeneLOSIncSelectedOption(beneLOS) {
    const workFieldsWrapperId = $(beneLOS).closest(".panel-collapse").attr("id");
    const rowId = workFieldsWrapperId.split("-")[1];
    const increaseValue = $(beneLOS).find("option:selected").data("increase");

    $(`#${workFieldsWrapperId} BeneLOSMonths-${rowId}`).val(increaseValue);

    $(`#${workFieldsWrapperId} [name='BeneLOSInc'] option`).each(function () {
        if ($(this).data("increase") == increaseValue) {
            $(`#${workFieldsWrapperId} [name='BeneLOSInc']`).val($(this).val()).trigger("change");
            return false;
        }
    });
}

function toogleIrisEmploymentField(id) {
    let isMatching = $("#Status-" + id).val() === $("#WorkStatusEmployment").val() && $("#CurrentLocalization").val() === $("#LocSI").val();
    $("#StatusEmploymentOption").toggleClass("hidden", !isMatching);
    $("#OthersStatusOption").toggleClass("hidden", isMatching);
}

//Work Book Chart
const defaultDuration = "00-00-00";

function generateWorkBookChart() {
    const ZVVP = $("#ZVVP").val() || defaultDuration;
    const SVDD = $("#SVDD").val() || defaultDuration;
    const [yearsSVDD, monthsSVDD, daysSVDD] = SVDD.split("-");

    const yearShort = $("#YearShort").val();
    const monthShort = $("#MonthShort").val();
    const dayShort = $("#DayShort").val();

    $("#LengthOfService").text(`${yearsSVDD}${yearShort} ${monthsSVDD}${monthShort} ${daysSVDD}${dayShort}`);

    const data = {
        labels: [
            "ZVVP " + ZVVP,
            "SVDD " + SVDD
        ],
        datasets: [{
            data: [ZVVP.replace(/-/g, ""), SVDD.replace(/-/g, "")],
            backgroundColor: [
                'rgb(250,175,20)',
                'rgb(255,233,187)'
            ],
            cutout: '70%',
            circumference: 180,
            rotation: 270
        }]
    };

    const config = {
        type: 'doughnut',
        data,
        options: {
            aspectRatio: 2,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    callbacks: {
                        label: function (context) {
                            return context.label || '';
                        }
                    }
                }
            }
        }
    };

    new Chart(
        document.getElementById('WorkBookChart'),
        config
    );
}

function recalculateWorkBookChart() {
    $.ajax({
        type: "GET",
        url: $("#RecalculateWorkBookChartUrl").val(),
        data: {
            worker: $("#ModelWorker").val(),
            date: moment($("#CalculationDate").val(), $("#DateFormat").val().toUpperCase()).toISOString()
        },
        success: function (data) {
            if (data) {
                let beginDate = " ";
                let endDate = " ";

                if (data.EmployeeWorkExperiences.length > 0) {
                    const firstWorkExperience = data.EmployeeWorkExperiences[data.EmployeeWorkExperiences.length - 1];
                    const lastWorkExperience = data.EmployeeWorkExperiences[0];
                    beginDate = firstWorkExperience.Begin ? moment(firstWorkExperience.Begin).format($("#DateFormat").val().toUpperCase()) : " ";
                    endDate = lastWorkExperience.End ? moment(lastWorkExperience.End).format($("#DateFormat").val().toUpperCase()) : " ";
                }

                $("#WorkBookDateStart").text(beginDate);
                $("#WorkBookDateEnd").text(endDate);
                $("#SVDD").val(data.SVDD);
                $("#ZVVP").val(data.ZVVP);
                $("#WorkBookChart").remove();
                $(".chart-wapper").prepend("<canvas id='WorkBookChart'></canvas>")
                generateWorkBookChart();
            }
        },
    });
}