using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNetCore.Components;
using RpgRoller.Contracts;

namespace RpgRoller.Components.Pages.HomeControls;

[ExcludeFromCodeCoverage]
public partial class AuthSection
{
    private async Task SubmitRegisterAsync()
    {
        RegisterState.ResetValidation();

        var model = RegisterState.Model;
        if (string.IsNullOrWhiteSpace(model.Username))
            RegisterState.Errors["username"] = "Username is required.";

        if (string.IsNullOrWhiteSpace(model.DisplayName))
            RegisterState.Errors["displayName"] = "Display name is required.";

        if (string.IsNullOrWhiteSpace(model.Password) || model.Password.Length < 8)
            RegisterState.Errors["password"] = "Password must be at least 8 characters.";

        if (RegisterState.Errors.Count > 0)
        {
            RegisterState.ErrorMessage = "Resolve validation issues before submitting.";
            return;
        }

        IsSubmitting = true;
        try
        {
            _ = await ApiClient.RequestAsync<UserSummary>("POST", "/api/auth/register", new RegisterRequest(model.Username.Trim(), model.Password, model.DisplayName.Trim()));

            model.Password = string.Empty;
            RegisterState.ErrorMessage = "Registration successful. You can log in now.";
        }
        catch (ApiRequestException ex)
        {
            if (ex.Message.Contains("already taken", StringComparison.OrdinalIgnoreCase))
                RegisterState.Errors["username"] = "Username is already taken. Choose another one.";
            else
                RegisterState.ErrorMessage = ex.Message;
        }
        finally
        {
            IsSubmitting = false;
        }
    }

    private async Task SubmitLoginAsync()
    {
        LoginState.ResetValidation();

        var model = LoginState.Model;
        if (string.IsNullOrWhiteSpace(model.Username))
            LoginState.Errors["username"] = "Username is required.";

        if (string.IsNullOrWhiteSpace(model.Password))
            LoginState.Errors["password"] = "Password is required.";

        if (LoginState.Errors.Count > 0)
        {
            LoginState.ErrorMessage = "Resolve validation issues before submitting.";
            return;
        }

        IsSubmitting = true;
        try
        {
            _ = await ApiClient.RequestAsync<UserSummary>("POST", "/api/auth/login", new LoginRequest(model.Username.Trim(), model.Password));

            model.Password = string.Empty;
            await LoggedIn.InvokeAsync();
        }
        catch (ApiRequestException ex)
        {
            LoginState.ErrorMessage = ex.Message;
        }
        finally
        {
            IsSubmitting = false;
        }
    }

    [Inject]
    private RpgRollerApiClient ApiClient { get; set; } = null!;

    private FormState<RegisterFormModel> RegisterState { get; } = new();
    private FormState<LoginFormModel> LoginState { get; } = new();
    private bool IsSubmitting { get; set; }

    [Parameter]
    public string? StatusMessage { get; set; }

    [Parameter]
    public bool StatusIsError { get; set; }

    [Parameter]
    public EventCallback LoggedIn { get; set; }
}