using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows.Input;

namespace MaUI
{
    public partial class ListeEmails_VM : INotifyPropertyChanged
    {
        #region Variables
        private readonly ApiService _apiService;
        #endregion

        #region Liste observable
        public ObservableCollection<LOGS_DTO> Liste_Items { get; set; }
        #endregion

        #region Element sélectionnée
        private LOGS_DTO? _selectedItem;
        public LOGS_DTO? SelectedItem
        {
            get => _selectedItem;
            set
            {
                _selectedItem = value;
                OnPropertyChanged();
            }
        }
        #endregion

        #region Commands 
        public ICommand LoadCommand { get; }
        public ICommand EditCommand { get; }
        public ICommand DeleteCommand { get; }
        public ICommand CreateCommand { get; }
        #endregion

        #region Constructeur
        public ListeEmails_VM()
        {
            _apiService = new ApiService();
            Liste_Items = new ObservableCollection<LOGS_DTO>();

            // Initialisation des commandes
            LoadCommand = new Command(async () => await LoadDataAsync());
            EditCommand = new Command(async () => await EditSelectedItemAsync(), () => SelectedItem != null);
            DeleteCommand = new Command(async () => await DeleteSelectedItemAsync(), () => SelectedItem != null);
            CreateCommand = new Command(async () => await CreateNewItemAsync());

            // Charger initialement les données
            _ = LoadDataAsync(); 
        }
        #endregion

        #region Méthodes
        public async Task LoadDataAsync()
        {
            try
            {
                var items = await _apiService.GetAll_Async<LOGS_DTO>("api/LOGS_DTO");
                Liste_Items.Clear();
                foreach (var item in items)
                {
                    Liste_Items.Add(item);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Erreur lors du chargement des données : {ex.Message}");
                await Application.Current!.MainPage!.DisplayAlert(
                    "Erreur",
                    $"Erreur lors du chargement des données : {ex.Message}",
                    "OK");
            }
        }

        public async Task EditSelectedItemAsync()
        {
            if (SelectedItem != null && Application.Current?.MainPage?.Navigation != null)
            {
                await Application.Current.MainPage.Navigation.PushAsync(new LOGS_Detail_Page(SelectedItem));
            }
            else
            {
                Console.WriteLine("Navigation ou SelectedItem est null.");
                await Application.Current!.MainPage!.DisplayAlert(
                    "Erreur",
                    $"Navigation ou SelectedItem est null.",
                    "OK");
            }
        }

        public async Task DeleteSelectedItemAsync()
        {
            if (SelectedItem != null && Application.Current?.MainPage != null)
            {
                bool confirm = await Application.Current.MainPage.DisplayAlert(
                    "Confirmation",
                    "Voulez-vous vraiment supprimer cet élément ?",
                    "Oui", "Non");

                if (confirm)
                {
                    try
                    {
                        var result = await _apiService.Delete_Async<Guid>($"api/LOGS_DTO/{SelectedItem.ID}");
                        if (result)
                        {
                            Liste_Items.Remove(SelectedItem);
                            await Application.Current.MainPage.DisplayAlert("Succès", "Suppression effectuée.", "OK");
                        }
                        else
                        {
                            await Application.Current.MainPage.DisplayAlert("Erreur", "Suppression non effectuée.", "OK");
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Erreur lors de la suppression : {ex.Message}");
                        await Application.Current!.MainPage!.DisplayAlert(
                            "Erreur",
                            $"Erreur lors de la suppression : {ex.Message}",
                            "OK");
                    }
                }
            }
            else
            {
                Console.WriteLine("MainPage or SelectedItem est null.");
                await Application.Current!.MainPage!.DisplayAlert(
                    "Erreur",
                    $"MainPage or SelectedItem est null.",
                    "OK");
            }
        }

        public async Task CreateNewItemAsync()
        {
            if (Application.Current?.MainPage?.Navigation != null)
            {
                await Application.Current.MainPage.Navigation.PushAsync(new LOGS_Detail_Page(null));
            }
            else
            {
                Console.WriteLine("Navigation est null.");
                await Application.Current!.MainPage!.DisplayAlert(
                    "Erreur",
                    $"Navigation est null",
                    "OK");
            }
        }
        #endregion

        #region Implémentation de INotifyPropertyChanged pour notifier les changements
        public event PropertyChangedEventHandler? PropertyChanged = delegate { };

        protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion
    }
}


