using System;
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 ForgotPassword : FsBase
    {
        public string MailAddress { get; set; } = string.Empty;
        public ValidationStatus IsValidMail { get; set; } = ValidationStatus.None;
        
        public bool IsSubmitted { get; set; }
        public bool IsLoading { get; set; }
        public string? ErrorMessage { get; set; }

        public async Task SubmitRequest()
        {
            if (IsValidMail != ValidationStatus.Success) return;

            IsLoading = true;
            ErrorMessage = null;
            await InvokeAsync(StateHasChanged);

            try
            {
                await AuthService.InitiatePasswordReset(MailAddress, NavigationManager.BaseUri);
                IsSubmitted = true;
            }
            catch (Exception)
            {
                ErrorMessage = "Es gab ein Problem bei der Verarbeitung der Anfrage. Bitte versuche es später erneut oder wende dich an einen Administrator.";
            }
            finally
            {
                IsLoading = false;
                await InvokeAsync(StateHasChanged);
            }
        }

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