var isEditWorkItemEnable = false;
var selectedWorkItemForFilter = null;
var azureAuthenticationHeader;

$(document).ready(async function () {

    $('#txtStartTime, #txtEndTime').datetimepicker({
        format: 'm/d/Y h:i A',
        formatTime: 'h:i A',
        autoClose: true,
        todayHighlight: true,
        validateOnBlur: false
    });

    await IndexLibrary.InitializeSDK();

    const contextData = IndexLibrary.GetPanelContext();
    azureAuthenticationHeader = await IndexLibrary.GetAccessToken();
    isEditWorkItemEnable = !!contextData.EditWorkItem;

    await LoadWorkTypes();

    if (isEditWorkItemEnable)
        await populateCalendarFields(contextData);
    else
        await populateUserStoryFields(contextData);

    $("#btnClosePanel").on('click', IndexLibrary.ClosePanel);

    $("#txtFilter").on('keyup focus', debounce(function () {
        if (!$(this).prop("disabled")) {
            GetWorkItemSuggestions($(this).val().trim());
        }
    }, 150));
    $("#txtFilter").on('blur', function () {
        setTimeout(() => $("#taskSuggestions").hide(), 200); // delay to allow click on suggestion
    });
});

// ================== USER STORY ==================
async function populateUserStoryFields(contextData) {
    const timesheet = await loadTimesheetById(contextData.id || contextData.timesheetId);
    fillCommonFields(timesheet);

    if (timesheet.workItemId) {
        const wi = await loadWorkItemTitle(timesheet.workItemId);
        lockWorkItem(wi);
        $("#txtFilter").val(`${wi.title} #${wi.id}`);
    }
}

// ================== CALENDAR ==================
async function populateCalendarFields(contextData) {
    let workItemId = contextData.workItemId;
    if (workItemId) {

        const wi = await loadWorkItemTitle(workItemId);
        selectedWorkItemForFilter = {
            id: wi.id,
            title: wi.title || ""
        };
        $("#workItemId").val(selectedWorkItemForFilter.id);
        $("#txtFilter").val(`${selectedWorkItemForFilter.title} #${selectedWorkItemForFilter.id}`);
        $("#txtFilter").prop("disabled", false);
    }

    const timesheet = await loadTimesheetById(contextData.timesheetId);
    fillCommonFields(timesheet);
}
function showInlineError(message) {
    $("#timeRangeError").remove();

    $("#txtEndTime").after(
        `<div id="timeRangeError" style="color:red;font-size:12px;margin-top:4px;">
            ${message}
         </div>`
    );
}

function clearInlineError() {
    $("#timeRangeError").remove();
}

function validateLiveRange() {
    const startVal = $("#txtStartTime").val();
    const endVal = $("#txtEndTime").val();

    if (!startVal || !endVal) {
        clearInlineError();
        return;
    }

    try {
        const result = IndexLibrary.validateTimeRangeLocal(startVal, endVal);

        if (!result.isValid) {
            showInlineError(result.message);
        } else {
            clearInlineError();
        }

    } catch (e) {
        showInlineError("Invalid date format.");
    }
}
// ================== COMMON ==================
async function loadTimesheetById(timesheetId) {
    return IndexLibrary.PostRequest({
        endpoint: "/api/Timesheet/GetTimesheetById",
        body: JSON.stringify({
            organizationName: await IndexLibrary.GetAccountNameAsync(),
            timesheetId
        })
    }).then(r => r.json());
}

function fillCommonFields(ts) {
    $("#timesheetId").val(ts.timesheetId);
    $("#txtStartTime").val(convertDateForPicker(ts.workStarted));
    $("#txtEndTime").val(convertDateForPicker(ts.workEnded));
    $("#txtDescription").val(ts.description || "");
    $("#chkIsBillable").prop("checked", !!ts.isBillable);
    $("#txtWorkType").val(String(ts.workTypeId));
}

// ================== WORK ITEMS ==================
async function GetWorkItemSuggestions(filterText) {
    const project = await IndexLibrary.GetCurrentProjectName();
    const items = await IndexLibrary.GetRequest({
        endpoint: `/api/AzureDevops/GetFilteredWorkItemsEvolveAssist?filter=${encodeURIComponent(filterText)}&teamProject=${encodeURIComponent(project)}`,
        azureAuthenticationHeader: azureAuthenticationHeader,
        organizationName: await IndexLibrary.GetAccountNameAsync(),
    }).then(r => r.json());

    let html = items?.length
        ? "<div style='font-weight:600'>Work items</div>"
        : "<i>No matching work items</i>";

    items?.forEach(i => {
        html += `<div class="work-item-suggestion" onclick="addWorkItemToFilter(this)"
                    data-workitem-id="${i.id}"
                    data-workitem-title="${i.title.replace(/'/g, '&#39;')}">
                    ${i.title} <span style="color:gray">#${i.id}</span>
                 </div>`;
    });

    $("#taskSuggestions").html(html).show();
}

function addWorkItemToFilter(el) {
    selectedWorkItemForFilter = {
        id: $(el).data("workitem-id"),
        title: $(el).data("workitem-title")
    };
    $("#workItemId").val(selectedWorkItemForFilter.id);
    $("#txtFilter").val(`${selectedWorkItemForFilter.title} #${selectedWorkItemForFilter.id}`);
    $("#taskSuggestions").hide();
}

function lockWorkItem(wi) {
    selectedWorkItemForFilter = wi;
    $("#workItemId").val(wi.id);
    $("#txtFilter").val(wi.title).prop("disabled", true);
}

// ================== WORK TYPES ==================
async function LoadWorkTypes() {
    const types = await IndexLibrary.GetRequest({
        endpoint: `/api/TrackingWorkType/GetAll/${await IndexLibrary.GetAccountNameAsync()}`,
    }).then(r => r.json());

    types.forEach(t => {
        if (!t.isDeleted)
            $("#txtWorkType").append(`<option value="${t.id}">${t.trackingWorkTypeTitle}</option>`);
    });
}

// ================== UPDATE ==================
async function UpdateTimesheet() {
    if (!selectedWorkItemForFilter?.id)
        return Swal.fire({ icon: 'warning', title: 'Please select a Work Item' });

    await IndexLibrary.UpdateTimesheet();
    localStorage.setItem("timeSheetChanged", "true");
}

// ================== HELPERS ==================
async function loadWorkItemTitle(workItemId) {
    const wi = await IndexLibrary.GetWorkItemWithFields(workItemId, ["System.Title"]);
    return { id: wi.id, title: wi.fields["System.Title"] || "" };
}

function debounce(fn, delay) {
    let t;
    return function () {
        clearTimeout(t);
        t = setTimeout(() => fn.apply(this, arguments), delay);
    };
}

function convertDateForPicker(date) {
    return IndexLibrary.convertUtcToLocal(date);
}

async function DeleteTimesheet() {
    const timesheetId = $("#timesheetId").val();
    if (!timesheetId) return Swal.fire({ icon: 'warning', title: 'Timesheet ID is missing' });

    const result = await Swal.fire({
        title: 'Are you sure?',
        text: "This will Delete the timesheet",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes'
    });

    if (result.isConfirmed) {

        await IndexLibrary.DeleteTimesheet(Number(timesheetId));
        localStorage.setItem("timeSheetChanged", "true");

    }
}