using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using Microsoft.SharePoint.Client;
using SharepointToolbox.Services;

namespace SharepointToolbox.Views.Dialogs;

public partial class LibraryPickerDialog : Window
{
    private readonly ClientContext _ctx;
    private readonly IVersionCleanupService _libraryLister;
    private readonly ObservableCollection<LibraryItem> _items = new();

    public IReadOnlyList<string> SelectedLibraryTitles { get; private set; } = Array.Empty<string>();

    public LibraryPickerDialog(
        ClientContext ctx,
        IVersionCleanupService libraryLister,
        IReadOnlyCollection<string>? preselected = null)
    {
        InitializeComponent();
        _ctx = ctx;
        _libraryLister = libraryLister;
        LibrariesList.ItemsSource = _items;
        Loaded += async (_, _) => await LoadAsync(preselected ?? Array.Empty<string>());
    }

    private async Task LoadAsync(IReadOnlyCollection<string> preselected)
    {
        try
        {
            var titles = await _libraryLister.ListLibraryTitlesAsync(_ctx, CancellationToken.None);
            var preset = new HashSet<string>(preselected, StringComparer.OrdinalIgnoreCase);
            foreach (var t in titles)
            {
                var item = new LibraryItem { Title = t, IsSelected = preset.Contains(t) };
                item.PropertyChanged += OnItemChanged;
                _items.Add(item);
            }
            StatusText.Text = string.Format(
                Localization.TranslationSource.Instance["librarypicker.loaded"],
                _items.Count);
            UpdateOkEnabled();
        }
        catch (Exception ex)
        {
            StatusText.Text = $"Error: {ex.Message}";
        }
    }

    private void OnItemChanged(object? sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == nameof(LibraryItem.IsSelected)) UpdateOkEnabled();
    }

    private void UpdateOkEnabled()
        => OkButton.IsEnabled = _items.Any(i => i.IsSelected);

    private void SelectAll_Click(object sender, RoutedEventArgs e)
    {
        foreach (var i in _items) i.IsSelected = true;
    }

    private void SelectNone_Click(object sender, RoutedEventArgs e)
    {
        foreach (var i in _items) i.IsSelected = false;
    }

    private void Ok_Click(object sender, RoutedEventArgs e)
    {
        SelectedLibraryTitles = _items.Where(i => i.IsSelected).Select(i => i.Title).ToList();
        DialogResult = true;
        Close();
    }

    private void Cancel_Click(object sender, RoutedEventArgs e)
    {
        DialogResult = false;
        Close();
    }

    protected override void OnClosed(EventArgs e)
    {
        foreach (var i in _items) i.PropertyChanged -= OnItemChanged;
        base.OnClosed(e);
    }

    public class LibraryItem : INotifyPropertyChanged
    {
        private bool _isSelected;
        public string Title { get; init; } = string.Empty;
        public bool IsSelected
        {
            get => _isSelected;
            set
            {
                if (_isSelected == value) return;
                _isSelected = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsSelected)));
            }
        }
        public event PropertyChangedEventHandler? PropertyChanged;
    }
}
