var workItemsSuggestionsTimer;
var isEditWorkItemEnable = false;
var organizationName = '';

$(document).ready(function () {
    $('#txtStartTime').datetimepicker({
        format: 'm/d/Y h:i A',
        formatTime: 'h:i A',
        validateOnBlur: false
    });
    $('#txtEndTime').datetimepicker({
        format: 'm/d/Y h:i A',
        formatTime: 'h:i A',
        validateOnBlur: false
    });
    $('#txtStartTime, #txtEndTime').on('change keyup blur', function () {
        validateLiveRange();
    });


    IndexLibrary.InitializeSDK().then(async function () {
        const contextData = IndexLibrary.GetPanelContext();
        organizationName = await IndexLibrary.GetAccountNameAsync();
        isEditWorkItemEnable = !!contextData.EditWorkItem;

        if ((contextData.id === undefined || contextData.id === '' || contextData.id === null) &&
            (contextData.workItemIds && contextData.workItemIds.length > 0)) {
            $("#workItemId").val(contextData.workItemIds[0].toString());
        } else {
            $("#workItemId").val(contextData.id);
        }

        if ($("#workItemId").val()) {
            const wi = await loadWorkItemTitle($("#workItemId").val());
            lockWorkItem(wi);
        }

        if (isEditWorkItemEnable) {
            enableWorkItemSearch();
        } else {
            disableWorkItemSearch();
        }


        if (contextData.startDateTime) {
            const start = new Date(contextData.startDateTime);
            $('#txtStartTime').val(formatDateForPicker(start));
            const end = new Date(start);
            end.setMinutes(end.getMinutes() + 30);
            $('#txtEndTime').val(formatDateForPicker(end));
        }

        await LoadWorkTypes();



    });

    $("#btnClosePanel, #btnCloseCross").off('click').on('click', function () {
        IndexLibrary.ClosePanel();
    });

    $("#txtFilter").on('keyup focus', function () {
        if ($(this).prop("disabled")) return;
        clearTimeout(workItemsSuggestionsTimer);
        const val = $(this).val().trim();
        if (val) {
            workItemsSuggestionsTimer = setTimeout(() => {
                GetWorkItemSuggestions(val);
                $("#taskSuggestions").show();
            }, 200);
        } else {
            $("#taskSuggestions").hide();
        }
    });
});

function disableWorkItemSearch() {
    $("#txtFilter").prop("disabled", true);
    $("#taskSuggestions").hide();
}

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.");
    }
}


function enableWorkItemSearch() {
    $("#txtFilter").prop("disabled", false).val("");
}

function formatDateForPicker(date) {
    const mm = String(date.getMonth() + 1).padStart(2, '0');
    const dd = String(date.getDate()).padStart(2, '0');
    const yyyy = date.getFullYear();
    let hours = date.getHours();
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const ampm = hours >= 12 ? 'PM' : 'AM';
    hours = hours % 12 || 12;
    return `${mm}/${dd}/${yyyy} ${hours}:${minutes} ${ampm}`;
}

async function GetWorkItemSuggestions(filterText) {
    const project = await IndexLibrary.GetCurrentProjectName();
    const response = await IndexLibrary.GetRequest({
        endpoint: `/api/AzureDevops/GetFilteredWorkItemsEvolveAssist?filter=${encodeURIComponent(filterText)}&teamProject=${encodeURIComponent(project)}`
    });

    if (!response.ok) {
        $("#taskSuggestions").html("<i>No work items found</i>").show();
        return;
    }

    const items = await response.json();

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

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

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

function selectWorkItem(el) {
    const workItem = {
        id: $(el).data("id"),
        title: $(el).data("title")
    };
    setWorkItemFilterInput(workItem);
    $("#taskSuggestions").hide();
}

function setWorkItemFilterInput(workItem) {
    $("#workItemId").val(workItem.id);
    $("#txtFilter").val(`${workItem.title} #${workItem.id}`);
}


async function fetchWorkItemTitle(workItemId) {
    const project = await IndexLibrary.GetCurrentProjectName();
    const response = await IndexLibrary.GetRequest({
        endpoint: `/api/AzureDevops/GetFilteredWorkItemsEvolveAssist?filter=&teamProject=${encodeURIComponent(project)}`
    });

    if (!response.ok) {
        return null;
    }

    const items = await response.json();

    const matched = items.find(wi => wi.id == workItemId);
    return matched ? matched.title : null;
}

async function LoadWorkTypes() {
    const org = organizationName || await IndexLibrary.GetAccountNameAsync();
    const response = await IndexLibrary.GetRequest({
        endpoint: `/api/TrackingWorkType/GetAll/${org}`
    });

    if (!response.ok) {
        console.error('Failed to load work types', response.status, response.statusText);
        return;
    }

    let types = [];
    try {
        types = await response.json();
    } catch (error) {
        console.error('Failed to parse work types response', error);
        return;
    }

    if (!Array.isArray(types)) {
        return;
    }

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

async function SaveTimesheet() {
    const workItemId = $("#workItemId").val();
    if (!workItemId) return Swal.fire({ icon: 'warning', title: 'Please select a Work Item first' });
    await IndexLibrary.SaveTimesheet(workItemId);
    localStorage.setItem("timeSheetChanged", "true");
}

function CloseEditPanel() {
    IndexLibrary.ClosePanel();
}
async function loadWorkItemTitle(workItemId) {

    const fields = ["System.Title"];
    const workItem = await IndexLibrary.GetWorkItemWithFields(workItemId, fields);

    return {
        id: workItem.id,
        title: workItem.fields["System.Title"] || ""
    };
}
function lockWorkItem(wi) {
    selectedWorkItemForFilter = wi;
    $("#workItemId").val(wi.id);
    $("#txtFilter").val(`${wi.title} #${wi.id}`).prop("disabled", true);
}
