using salesbook.Shared.Core.Dto;
using salesbook.Shared.Core.Dto.Contact;
using salesbook.Shared.Core.Dto.PageState;
using salesbook.Shared.Core.Dto.Users;
using salesbook.Shared.Core.Interface;

namespace salesbook.Shared.Core.Services;

public class PreloadService(IManageDataService manageData, UserListState userState)
{
    public async Task PreloadUsersAsync()
    {
        if (userState.IsLoaded || userState.IsLoading)
            return;

        userState.IsLoading = true;

        var users = await manageData.GetContact(new WhereCondContact { FlagStato = "A" });

        var sorted = users
            .Where(u => !string.IsNullOrWhiteSpace(u.RagSoc))
            .OrderBy(u => char.IsLetter(char.ToUpper(u.RagSoc[0])) ? char.ToUpper(u.RagSoc[0]).ToString() : "ZZZ")
            .ThenBy(u => u.RagSoc)
            .ToList();

        userState.GroupedUserList = BuildGroupedList(sorted);
        userState.FilteredGroupedUserList = userState.GroupedUserList;
        userState.AllUsers = users;

        userState.NotifyUsersLoaded();
    }

    private static List<UserDisplayItem> BuildGroupedList(List<ContactDTO> users)
    {
        var grouped = new List<UserDisplayItem>();
        string? lastHeader = null;

        foreach (var user in users)
        {
            var firstChar = char.ToUpper(user.RagSoc[0]);
            var currentLetter = char.IsLetter(firstChar) ? firstChar.ToString() : "#";

            var showHeader = currentLetter != lastHeader;
            lastHeader = currentLetter;

            grouped.Add(new UserDisplayItem
            {
                User = user,
                ShowHeader = showHeader,
                HeaderLetter = currentLetter
            });
        }

        return grouped;
    }
}