using Blazored.Toast.Configuration;
using Blazored.Toast.Services;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.JSInterop;
using System.Net.Http.Json;
using ReAct_PME.WebUI.ServicesUI;

namespace ReAct_PME.WebUI.Pages.AuthLogin
{
    public partial class AuthLogin : ComponentBase
    {
        [Inject] private NavigationManager Navigation { get; set; } = default!;
        [Inject] private HttpClient Http { get; set; } = default!;
        [Inject] private Blazored.LocalStorage.ILocalStorageService localStorage { get; set; } = default!;
        [Inject] private ReAct_PME.WebUI.ServicesUI.AuthService AuthService { get; set; } = default!;
        [Inject] private AuthenticationStateProvider AuthenticationStateProvider { get; set; } = default!;
        [Inject] private IJSRuntime JS { get; set; } = default!;
        [Inject] private IToastService ToastService { get; set; } = default!;
        private LoginModel loginModel = new();
        private string? errorMessage;

        public class LoginModel
        {
            public string Username { get; set; } = string.Empty;
            public string Password { get; set; } = string.Empty;
        }
        public class LoginResponse
        {
            public string Token { get; set; } = string.Empty;
        }

        private bool IsAuthorized { get; set; } = true;

        [JSInvokable]
        public async Task SendToServer(string imageData)
        {
            var content = new StringContent($"{{\"imageBase64\": \"{imageData}\"}}",
                System.Text.Encoding.UTF8, "application/json");

            var response = await Http.PostAsync("/api/face/verify", content);
            var result = await response.Content.ReadAsStringAsync();

            if (result == "unauthorized")
            {
                IsAuthorized = false;
                errorMessage = $"Connexion refus�e";
            }
            else
            {
                if ((AuthService.FirstName!.ToLower() + "_" + AuthService.LastName!.ToLower()) == result.ToLower())
                {
                    IsAuthorized = true;
                }
                else
                {
                    IsAuthorized = false;
                    errorMessage = $"Connexion refus�e";
                }

            }

        }

        private async Task StartCamera()
        {
            await JS.InvokeVoidAsync("faceCapture.startCamera");
        }

        private async Task CapturePhoto()
        {
            await StartCamera();
            // Capture la photo depuis le flux vid�o
            await JS.InvokeVoidAsync("faceCapture.captureAndSend",
                DotNetObjectReference.Create(this));
        }

        private async Task HandleLogin()
        {
            try
            {
                var response = await Http.PostAsJsonAsync("api/auth/login", loginModel);
                response.EnsureSuccessStatusCode();
                var loginResponse = await response.Content.ReadFromJsonAsync<LoginResponse>();

                if (loginResponse is not null && !string.IsNullOrWhiteSpace(loginResponse.Token))
                {
                    await localStorage.SetItemAsync("authToken", loginResponse.Token); // Stocke le token
                    AuthService.SetToken(loginResponse.Token);
                    if (AuthenticationStateProvider is CustomAuthenticationStateProvider authProvider)
                    {
                        //await CapturePhoto();
                        if (IsAuthorized == true)
                        {
                            authProvider.NotifyUserAuthentication(loginResponse.Token);
                            Navigation.NavigateTo("/chatroom_base/0");
                        }
                        else
                        {
                            authProvider.Deconnect();
                            AuthService.Deconnect();
                        }
                    }
                }

            }
            catch(Exception ex)
            {
                ToastService.ShowError($"Erreur : Modification impossible : {ex.Message}", settings => { settings.Timeout = 2000; settings.IconType = IconType.None; settings.Position = ToastPosition.BottomCenter; });
                errorMessage = $"Erreur serveur : {ex.Message}";
            }
        }
    }
}
