using AyCode.Core.Loggers;
using AyCode.Utils.Extensions;
using FruitBank.Common.Models;
using FruitBankHybrid.Shared.Databases;
using FruitBankHybrid.Shared.Services.Loggers;
using FruitBankHybrid.Shared.Services.SignalRs;
using Mango.Nop.Core.Dtos;
using Mango.Nop.Core.Loggers;
using Mango.Nop.Core.Models;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;

namespace FruitBankHybrid.Shared.Pages;

public partial class Login : ComponentBase
{
    [Inject] public required IEnumerable<IAcLogWriterClientBase> LogWriters { get; set; }
    [Inject] public required FruitBankSignalRClient FruitBankSignalRClient { get; set; }
    [Inject] public required LoggedInModel LoggedInModel { get; set; }
    [Inject] public required NavigationManager NavManager{ get; set; }

    private ILogger _logger = null!;
    private CustomerDto? SelectedUser { get; set; }
    private string PasswordValue { get; set; } = string.Empty;
    private MgLoginModelResponse? LoginModelResponse { get; set; }
    private string _rolesText = string.Empty;
    
    [CascadingParameter]
    public EventCallback UpdateStyle { get; set; }

    protected override async Task OnInitializedAsync()
    {
        _logger = new LoggerClient<Login>(LogWriters.ToArray());
        _logger.Info("OnInitializedAsync");

        if (!LoggedInModel.IsLoggedIn)
        {
            await LoadMeasuringUsersAsync();
        }
        else
        {
            _rolesText = string.Join("; ", LoggedInModel.CustomerRoles.Select(x => x.Name));
        }

        await base.OnInitializedAsync();
    }

    private async Task LoadMeasuringUsersAsync()
    {
        using (await ObjectLock.GetSemaphore<CustomerDto>().UseWaitAsync())
        {
            if (LoggedInModel.MeasuringUsers.Count == 0)
            {
                LoggedInModel.MeasuringUsers = await FruitBankSignalRClient.GetMeasuringUsers() ?? [];
                SelectedUser = LoggedInModel.MeasuringUsers.FirstOrDefault();
            }
        }
    }

    private async Task OnLoginClick()
    {
        if (LoggedInModel.IsLoggedIn) return;

        _rolesText = string.Empty;

        if (!ValidateLoginInput()) return;

        // Use the simplified LoginAsync from LoggedInModel
        if(await LoggedInModel.LoginAsync(SelectedUser!.Email, PasswordValue))
        {
            _rolesText = string.Join("; ", LoggedInModel.CustomerRoles.Select(x => x.Name));
        }

        await UpdateStyle.InvokeAsync();
        
        if (LoggedInModel.IsLoggedIn)
        {
            NavManager.NavigateTo("/");
        }
            
        StateHasChanged();
    }

    private bool ValidateLoginInput()
    {
        if (SelectedUser == null || PasswordValue.IsNullOrWhiteSpace())
        {
            LoginModelResponse = new MgLoginModelResponse
            {
                ErrorMessage = "Válasszon felhsználót és adja meg a jelszavát!"
            };
            return false;
        }
        return true;
    }

    protected async Task OnPasswordKeyDown(KeyboardEventArgs e)
    {
        if (!LoggedInModel.IsLoggedIn && e.Key == "Enter") await OnLoginClick();
    }

    private string GetImageFileName(CustomerDto employee)
    {
        return string.Empty;
    }
}