using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;

namespace MaUI;

public partial class AuthLogin_VM : INotifyPropertyChanged
{
    #region Variables
    private readonly ApiService _apiService;
    #endregion

    #region Propriétés

    #region Commands
    public ICommand ValiderCommand { get; set; }
    public ICommand AnnulerCommand { get; }
    #endregion

    #region Element de saisie
    private LoginModel _selectedItem = null!;
    public LoginModel SelectedItem
    {
        get => _selectedItem;
        set
        {
            _selectedItem = value;
            OnPropertyChanged();
            //MettreAJourSelection();
        }
    }
    #endregion



    #endregion

    #region Constructeur
    public AuthLogin_VM()
    {
        SelectedItem = new();

        ValiderCommand = new Command(ExecuterValidation);
        AnnulerCommand = new Command(ExecuterAnnulation);

        _apiService = new ApiService();
    }
    #endregion

    #region Méthodes actions
    private async void ExecuterAnnulation()
    {
        if (Application.Current?.MainPage != null)
        {
            bool reponse = await Application.Current.MainPage.DisplayAlert(
                "Confirmation",
                "Voulez-vous vraiment annuler les modifications ?",
                "Oui",
                "Non");

            if (reponse)
            {
                // Retour à la page précédente
                //await Application.Current.MainPage.Navigation.PopAsync();
            }
        }
    }

    private async void ExecuterValidation()
    {
        if (Application.Current?.MainPage != null)
        {
            if (SelectedItem != null)
            {
                bool rep = false;
                string msg = "";

                rep = await _apiService.Connexion(SelectedItem);

                if (!rep)
                {
                    msg = "Votre connexion est refusée.";
                    await Application.Current.MainPage.DisplayAlert("Erreur", msg, "OK");
                }
                else 
                {
                    _selectedItem = new LoginModel();
                    await Application.Current.MainPage.Navigation.PushAsync(new MainPage());
                }


            }
        }
    }

    #endregion

    #region Implémentation de INotifyPropertyChanged
    public event PropertyChangedEventHandler? PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
    {
        if (propertyName is null)
            return;

        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion
}

#region Autres classes
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;
}
#endregion