using CommunityToolkit.Maui.Alerts;
using CommunityToolkit.Maui.Core;
using Plugin.Firebase.CloudMessaging;
using System.Drawing;
using WorkFlowCheck.MAUI.Helper;
using WorkFlowCheck.MAUI.Pages.NFC;
using WorkFlowCheck.MAUI.Services.Interfaces;

namespace WorkFlowCheck.MAUI.Pages.Security;

public partial class LoginPage : BasePage
{
    private IUserService _userService;
    private ISyncService _syncService;
    public LoginPage()
    {
        InitializeComponent();
       
        SetContent(LoginContent);
        _userService = MauiProgram.ServiceProvider.GetRequiredService<IUserService>();
        _syncService = MauiProgram.ServiceProvider.GetRequiredService<ISyncService>();
        Title = $"Workflow Check Application ({SystemHelper.ProgramVersion})";
    }
    private async void OnLoginClicked(object sender, EventArgs e)
    {
        LoadingIndicator.IsRunning = true;
        LoadingIndicator.IsVisible = true;
        LoginBtn.IsEnabled = false;
        UsernameEntry.IsEnabled = false;
        PasswordEntry.IsEnabled = false;
        try
        {
            var response = await _userService.Authenticate(UsernameEntry.Text.ToString(), PasswordEntry.Text.ToString());

            if (response != null && response.IsSuccess)
            {
                _userService.SetCurrentUser(response.Data);
                SystemHelper.SystemUserDTO = response.Data;

                var needFCM = false;
                foreach (var role in response.Data.RoleDTO)
                {
                    if (role.CanEnableBlocked)
                    {
                        needFCM = true;
                        break;
                    }
                }
                if (needFCM)
                {
                    await InitFirebase();
                }
                
                var wFCUser = Newtonsoft.Json.JsonConvert.SerializeObject(response.Data);
                await SecureStorage.Default.SetAsync("WFCUser", "wFCUser");
                await SecureStorage.Default.SetAsync("AuthToken", response.Data.JwtToken);

                await Shell.Current.GoToAsync("//SyncPage");
            }
            else
            {

                var visualOptions = new SnackbarOptions
                {
                    ActionButtonTextColor = Colors.Yellow,
                    CornerRadius = new CornerRadius(10),
                    Font = Microsoft.Maui.Font.SystemFontOfSize(16),
                    BackgroundColor = Microsoft.Maui.Graphics.Color.Parse("Red"),
                    TextColor = Colors.Yellow

                };
                var snackbar = Snackbar.Make(
                                                "Invalid login credentials.",
                                                duration: TimeSpan.FromSeconds(10),
                                                action: () => Console.WriteLine("Snackbar dismissed"),
                                                actionButtonText: "OK",
                                                visualOptions: visualOptions
                                            );

                await snackbar.Show();
            }
        }
        catch (Exception ex)
        {
            var visualOptions = new SnackbarOptions
            {
                ActionButtonTextColor = Colors.Yellow,
                CornerRadius = new CornerRadius(10),
                Font = Microsoft.Maui.Font.SystemFontOfSize(16),
                BackgroundColor = Microsoft.Maui.Graphics.Color.Parse("Red"),
                TextColor = Colors.Yellow

            };
            var snackbar = Snackbar.Make(
                                            "Invalid login credentials.",
                                            duration: TimeSpan.FromSeconds(10),
                                            action: () => Console.WriteLine("Snackbar dismissed"),
                                            actionButtonText: "OK",
                                            visualOptions: visualOptions
                                        );

            await snackbar.Show();

        }
        finally
        {
            LoginBtn.IsEnabled = true;
            LoadingIndicator.IsRunning = false;
            LoadingIndicator.IsVisible = false;
            UsernameEntry.IsEnabled = true;
            PasswordEntry.IsEnabled = true;

        }

    }
    private async void OnLoginNFCClicked(object sender, EventArgs e)
    {
        LoadingIndicator.IsRunning = true;
        LoadingIndicator.IsVisible = true;
        LoginBtn.IsEnabled = false;
        LoginNFCBtn.IsEnabled = false;
        UsernameEntry.IsEnabled = false;
        PasswordEntry.IsEnabled = false;
        try
        {
            var nFCCode = await NFCWaiter.ShowModalAsync();
            if (!string.IsNullOrEmpty(nFCCode))
            {
                var response = await _userService.AuthenticateNFC(nFCCode);

                if (response != null && response.IsSuccess)
                {
                    _userService.SetCurrentUser(response.Data);
                    SystemHelper.SystemUserDTO = response.Data;

                    var wFCUser = Newtonsoft.Json.JsonConvert.SerializeObject(response.Data);
                    await SecureStorage.Default.SetAsync("WFCUser", "wFCUser");
                    await SecureStorage.Default.SetAsync("AuthToken", response.Data.JwtToken);

                    await Shell.Current.GoToAsync("//SyncPage");
                }
                else
                {

                    var visualOptions = new SnackbarOptions
                    {
                        ActionButtonTextColor = Colors.Yellow,
                        CornerRadius = new CornerRadius(10),
                        Font = Microsoft.Maui.Font.SystemFontOfSize(16),
                        BackgroundColor = Microsoft.Maui.Graphics.Color.Parse("Red"),
                        TextColor = Colors.Yellow

                    };
                    var snackbar = Snackbar.Make(
                                                    "Invalid login credentials.",
                                                    duration: TimeSpan.FromSeconds(10),
                                                    action: () => Console.WriteLine("Snackbar dismissed"),
                                                    actionButtonText: "OK",
                                                    visualOptions: visualOptions
                                                );

                    await snackbar.Show();
                }
            }
        }
        catch (Exception)
        {

            throw;
        }
        finally
        {
            LoginBtn.IsEnabled = true;
            LoginNFCBtn.IsEnabled = true;
            LoadingIndicator.IsRunning = false;
            LoadingIndicator.IsVisible = false;
            UsernameEntry.IsEnabled = true;
            PasswordEntry.IsEnabled = true;
            LoginNFCBtn.IsEnabled = true;
        }

    }

    private async Task InitFirebase()
    {
        try
        {
            await CrossFirebaseCloudMessaging.Current.CheckIfValidAsync();
            var token = await CrossFirebaseCloudMessaging.Current.GetTokenAsync();
            
            await _syncService.UploadFCMToken(token);
        }
        catch (Exception ex)
        {
            await SystemHelper.ShowSnackBar("FCM üzenetküldő inicializálása SIKERTELEN!",
                                                 SystemHelper.ColorToHex(Colors.Red),
                                                 SystemHelper.ColorToHex(Colors.Red),
                                                 SystemHelper.ColorToHex(Colors.Yellow),
                                                 15);
        }
    }
}