using CMSMicroservice.Protobuf.Protos.OtpToken;
using CMSMicroservice.Protobuf.Protos.User;
using CMSMicroservice.Protobuf.Validator.User;
using BackOffice.Common.Utilities;
using Blazored.LocalStorage;
using Microsoft.AspNetCore.Components;
using MudBlazor;
using VerifyOtpTokenRequest = CMSMicroservice.Protobuf.Protos.User.VerifyOtpTokenRequest;
using CreateNewOtpTokenRequest = CMSMicroservice.Protobuf.Protos.OtpToken.CreateNewOtpTokenRequest;
using VerifyOtpTokenRequestValidator = CMSMicroservice.Protobuf.Validator.User.VerifyOtpTokenRequestValidator;

namespace BackOffice.Pages.Login;
public partial class VerifyCodePage
{
    [Parameter]
    public string Mobile { get; set; }

    private bool _isLoading;
    private VerifyOtpTokenRequest _request = new() { Purpose = "login" };
    private VerifyOtpTokenRequestValidator _requestValidator = new();
    private MudForm _form;
    private Timer _timer;
    private int _currentCount = 120;

    [Inject]
    public UserContract.UserContractClient UserClient { get; set; }
    
    [Inject]
    public OtpTokenContract.OtpTokenContractClient OtpTokenClient { get; set; }

    protected override void OnInitialized()
    {
        StartTimer();
    }
    private async Task OnSubmitClick()
    {
        await _form.Validate();
        if (!_form.IsValid)
            return;

        _isLoading = true;
        StateHasChanged();

        _request.Mobile = Mobile.PersianToEnglish();
        _request.Code = _request.Code.PersianToEnglish();

        try
        {
            var result = await UserClient.VerifyOtpTokenAsync(_request);
            if (result.Success && result.Token != null)
            {
                await LocalStorageService.SetItemAsync(GlobalConstants.JwtTokenKey, result.Token);
                Navigation.NavigateTo(RouteConstance.HomePage, forceLoad: true);
            }
            else
            {
                Snackbar.Add(message: result.Message, severity: Severity.Error);
            }
        }
        catch (Exception ex)
        {
            var message = ex.Message.ExtractUserFriendlyMessage();
            Snackbar.Add(message: message, severity: Severity.Error);
        }

        _isLoading = false;
        StateHasChanged();


    }
    private async Task OnResendOtpClick()
    {
        _isLoading = true;
        StateHasChanged();

        try
        {
            await OtpTokenClient.CreateNewOtpTokenAsync(new CreateNewOtpTokenRequest
            {
                Mobile = Mobile,
                Purpose = "login"
            });
            StartTimer();
        }
        catch (Exception ex)
        {
            var message = ex.Message.ExtractUserFriendlyMessage();
            Snackbar.Add(message: message, severity: Severity.Error);
        }

        _isLoading = false;
        StateHasChanged();
    }

    private void StartTimer()
    {
        _currentCount = 120;
        _timer = new Timer(new TimerCallback(_ =>
        {
            if (_currentCount > 0)
            {
                _currentCount--;
                InvokeAsync(() =>
                {
                    StateHasChanged();
                });
            }
            else
            {
                _timer.Dispose();
            }
        }), null, 1000, 1000);
    }
}
