var licensedUsers = 0;
var totalLicenses = 0;
var baseAPIUrl = '';
var selectedUserForLicense = false;
LoadConfigPage();

async function ConvertType(id, customerEmail) {
    try {
        const response = await IndexLibrary.PutRequest({
            endpoint: `/api/PTSLicense/ToggleStandardAndManagerUser?userEmail=${encodeURIComponent(customerEmail)}&updatedBy=${encodeURIComponent(IndexLibrary.GetUserEmail())}`
        });

        if (!response.ok) {
            throw new Error('Failed to update user type.');
        }

        await LoadLicensedUsersTable();

        await IndexLibrary.ShowToast('success', 'User type updated successfully.');
    } catch (error) {
        console.error('Error updating user type:', error);
        await IndexLibrary.ShowToast('error', 'Failed to update user type.');
    }
}


async function LoadConfigPage() {
    selectedUserForLicense = false;
    $("#btnAddLicense").attr('disabled', 'disabled');

    await IndexLibrary.ensureSdkReady();
    const { baseAPIUrl: configuredBaseApiUrl } = await initializeIndexLibraryValues();
    baseAPIUrl = configuredBaseApiUrl;

    $("#noWorkTypesDefined").hide();
    await IndexLibrary.LoadWorkTypes(baseAPIUrl);
}

$(document).ready(async function () {
    PopulateWorkItemFieldsAndConfig();
    
    $(document).on('click', '#btnCreateWorkType', async function () {
        if (!baseAPIUrl) {
            const { baseAPIUrl: configuredBaseApiUrl } = await initializeIndexLibraryValues();
            baseAPIUrl = configuredBaseApiUrl;
        }
        IndexLibrary.HandleCreateWorkItemTypeClick({ apiUrl: baseAPIUrl });
    });

    $("#btnSaveConfiguration").on('click', async function () {
        const organizationName = await IndexLibrary.GetAccountNameAsync();
        const workItemFieldMappings = [{
            fieldName: "Customer",
            mappedField: $('#customerMapping').find(":selected").val(),
            organizationName: organizationName
        }];

        const selectedScope = $("#scopeProjectCheck").is(":checked") ? 1 : 0;
        const data = {
            defaultWorkLogTime: $("#workLogDefaultTime").val(),
            allWorkLogsBillableByDefault: $("#chkIsBillableByDefault").is(':checked'),
            organizationName: organizationName,
            reportScopeLevel: selectedScope,
            workItemFieldMaps: workItemFieldMappings,
            updatedBy: IndexLibrary.GetUserEmail()
        };

        try {
            const response = await IndexLibrary.PostRequest({
                endpoint: "/api/TimesheetSettings/UpsertSettings",
                body: data
            });

            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(errorText || 'Failed to save settings.');
            }

            await IndexLibrary.ShowToast('success', 'Settings saved successfully.');
        } catch (error) {
            await IndexLibrary.ShowToast('error', error && error.message ? error.message : 'Failed to save settings.');
        }
    });

    $('#scopeProjectCheck').on('click', function () {
        if ($(this).is(":checked")) {
            $("#scopeOrganizationCheck").prop("checked", false);
        } else {
            $("#scopeOrganizationCheck").prop("checked", true);
        }
    });
    $('#scopeOrganizationCheck').on('click', function () {
        if ($(this).is(":checked")) {
            $("#scopeProjectCheck").prop("checked", false);
        } else {
            $("#scopeProjectCheck").prop("checked", true);
        }
    });
    $('#licensedUserTypeStandard').on('click', function () {
        if ($(this).is(":checked")) {
            $("#licensedUserTypeManager").prop("checked", false);
        } else {
            $("#licensedUserTypeManager").prop("checked", true);
        }
    });
    $('#licensedUserTypeManager').on('click', function () {
        if ($(this).is(":checked")) {
            $("#licensedUserTypeStandard").prop("checked", false);
        } else {
            $("#licensedUserTypeStandard").prop("checked", true);
        }
    });
    $(document).on('click', function (e) {
        if (!e.target.classList.contains('suggestion') && e.target.id !== 'txtUserFilter') {
            $("#userSuggestions").hide();
        }
    });
});



async function EditWorkType(workTypeId, workTypeTitle, isDefault, color, isEffortIncluded) {
    if (!baseAPIUrl) {
        const { baseAPIUrl: configuredBaseApiUrl } = await initializeIndexLibraryValues();
        baseAPIUrl = configuredBaseApiUrl;
    }

    IndexLibrary.HandleEditWorkItemTypeClick({ apiUrl: baseAPIUrl, id: workTypeId, workType: workTypeTitle, workTypeDefault: isDefault, workTypeColor: color, workTypeEffortIncluded: isEffortIncluded });
}
async function DeleteWorkType(workTypeId) {
    const organizationName = await IndexLibrary.GetAccountNameAsync();
    const data = {
        trackingWorkTypeId: workTypeId,
        organizationName: organizationName,
        deletedBy: IndexLibrary.GetUserEmail()
    };

    try {
        const response = await IndexLibrary.PostRequest({
            endpoint: "/api/TrackingWorkType/DeleteTrackingWorkType",
            body: data
        });

        const json = await response.json().catch(() => ({}));

        if (response.ok) {
            await IndexLibrary.ShowToast('success', 'Work item type deleted successfully.');
            await IndexLibrary.LoadWorkTypes(baseAPIUrl);
        } else {
            await IndexLibrary.ShowToast('error', json.message || 'Failed to delete work item type.');
        }
    } catch (err) {
        await IndexLibrary.showAlertDialog({
            title: 'Error',
            text: 'An unexpected error occurred.',
            icon: 'error'
        });
        console.error(err);
    }
}
