using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Http;

namespace Guestlist.Components.Pages;

public partial class GuestList : ComponentBase
{
    [Inject]
    protected GuestEntryService GuestEntryService { get; set; } = default!;

    [Inject]
    protected IHttpContextAccessor HttpContextAccessor { get; set; } = default!;

    [Inject]
    protected AuthenticationStateProvider AuthenticationStateProvider { get; set; } = default!;

    [Inject]
    protected NavigationManager Navigation { get; set; } = default!;

    protected List<GuestEntryDocument>? GuestEntries { get; set; }
    protected bool ShowLeaveGuestList { get; set; }
    protected string SearchTerm { get; set; } = "";

    [SupplyParameterFromQuery(Name = "search")]
    public string? IncomingSearchTerm { get; set; }

    protected IEnumerable<GuestEntryDocument> FilteredGuestEntries
    {
        get
        {
            if (GuestEntries is null)
            {
                return [];
            }

            if (string.IsNullOrWhiteSpace(SearchTerm))
            {
                return GuestEntries;
            }

            var searchTerm = SearchTerm.Trim();

            return GuestEntries.Where(guest =>
                guest.Name.Contains(searchTerm, StringComparison.OrdinalIgnoreCase) ||
                (guest.Notes?.Contains(searchTerm, StringComparison.OrdinalIgnoreCase) == true) ||
                guest.AddedByUsername.Contains(searchTerm, StringComparison.OrdinalIgnoreCase));
        }
    }

    protected override async Task OnInitializedAsync()
    {
        SearchTerm = IncomingSearchTerm ?? "";

        var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;
        var isStaffUser =
            user.Identity?.IsAuthenticated == true &&
            (user.IsInRole(UserRoles.Admin) || user.IsInRole(UserRoles.Maintainer));

        var hasGuestAccess =
            HttpContextAccessor.HttpContext?.Session.GetString("GuestAccessGranted") == "true";

        if (!isStaffUser && !hasGuestAccess)
        {
            Navigation.NavigateTo("/guest");
            return;
        }

        ShowLeaveGuestList = !isStaffUser && hasGuestAccess;
        GuestEntries = await GuestEntryService.GetAllAsync();
    }
}
