using Blazorise;
using FoodsharingSiegen.Server.BaseClasses;
using FoodsharingSiegen.Server.Auth;
using FoodsharingSiegen.Shared.Helper;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using System.Threading.Tasks;

namespace FoodsharingSiegen.Server.Pages
{
    public partial class ResetPassword : FsBase
    {
        [Parameter]
        public string Token { get; set; } = string.Empty;

        public string NewPassword { get; set; } = string.Empty;
        public string ConfirmPassword { get; set; } = string.Empty;
        
        public ValidationStatus IsValidPassword { get; set; } = ValidationStatus.None;
        public ValidationStatus IsValidPasswordConfirmation { get; set; } = ValidationStatus.None;
        
        public string ErrorMessage { get; set; } = string.Empty;
        public bool IsSuccess { get; set; }
        public bool IsLoading { get; set; }
        public bool IsInitializing { get; set; } = true;
        public bool IsTokenValid { get; set; }

        protected override async Task OnInitializedAsync()
        {
            IsTokenValid = await AuthService.IsResetTokenValid(Token);
            IsInitializing = false;
        }

        public void ValidatePasswordConfirmation(ValidatorEventArgs args)
        {
            var confirmPassword = System.Convert.ToString(args.Value);
            if (string.IsNullOrWhiteSpace(confirmPassword))
            {
                args.Status = ValidationStatus.None;
                return;
            }

            args.Status = confirmPassword == NewPassword ? ValidationStatus.Success : ValidationStatus.Error;
        }

        public async Task SubmitReset()
        {
            if (IsValidPassword != ValidationStatus.Success || IsValidPasswordConfirmation != ValidationStatus.Success) return;

            IsLoading = true;
            ErrorMessage = string.Empty;
            await InvokeAsync(StateHasChanged);

            var result = await AuthService.ResetPassword(Token, NewPassword);

            if (result.Success)
            {
                IsSuccess = true;
            }
            else
            {
                ErrorMessage = result.Exception?.Message ?? "Ein Fehler ist aufgetreten.";
            }

            IsLoading = false;
            await InvokeAsync(StateHasChanged);
        }

        public async Task TextEdit_KeyUp(KeyboardEventArgs e)
        {
            if (e.Key == "Enter" && IsValidPassword == ValidationStatus.Success && IsValidPasswordConfirmation == ValidationStatus.Success)
            {
                await SubmitReset();
            }
        }
    }
}