using System.Windows;
using System.Windows.Controls;
using Microsoft.Extensions.DependencyInjection;
using SharepointToolbox.Core.Models;
using SharepointToolbox.ViewModels;
using SharepointToolbox.Views.Dialogs;
using SharepointToolbox.Views.Tabs;

namespace SharepointToolbox;

public partial class MainWindow : Window
{
    private readonly MainWindowViewModel _viewModel;

    public MainWindow(MainWindowViewModel viewModel, IServiceProvider serviceProvider)
    {
        InitializeComponent();
        _viewModel = viewModel;
        DataContext = viewModel;

        // Wire profile management dialog factory
        viewModel.OpenProfileManagementDialog = () => serviceProvider.GetRequiredService<ProfileManagementDialog>();

        // Wire global site picker dialog factory (same pattern as PermissionsView)
        viewModel.OpenGlobalSitePickerDialog = () =>
        {
            var factory = serviceProvider.GetRequiredService<Func<TenantProfile, SitePickerDialog>>();
            return factory(viewModel.SelectedProfile ?? new TenantProfile());
        };

        // Replace Permissions tab placeholder with the DI-resolved PermissionsView
        PermissionsTabItem.Content = serviceProvider.GetRequiredService<PermissionsView>();

        // Replace Storage tab placeholder with the DI-resolved StorageView
        StorageTabItem.Content = serviceProvider.GetRequiredService<StorageView>();

        // Replace Search tab placeholder with the DI-resolved SearchView
        SearchTabItem.Content = serviceProvider.GetRequiredService<SearchView>();

        // Replace Duplicates tab placeholder with the DI-resolved DuplicatesView
        DuplicatesTabItem.Content = serviceProvider.GetRequiredService<DuplicatesView>();

        // Versions cleanup tab
        VersionsTabItem.Content = serviceProvider.GetRequiredService<VersionCleanupView>();

        // Phase 4: Replace stub tabs with DI-resolved Views
        TransferTabItem.Content = serviceProvider.GetRequiredService<TransferView>();
        BulkMembersTabItem.Content = serviceProvider.GetRequiredService<BulkMembersView>();
        BulkSitesTabItem.Content = serviceProvider.GetRequiredService<BulkSitesView>();
        FolderStructureTabItem.Content = serviceProvider.GetRequiredService<FolderStructureView>();
        TemplatesTabItem.Content = serviceProvider.GetRequiredService<TemplatesView>();

        // Phase 7: User Access Audit
        UserAccessAuditTabItem.Content = serviceProvider.GetRequiredService<UserAccessAuditView>();

        // Replace Settings tab placeholder with the DI-resolved SettingsView
        SettingsTabItem.Content = serviceProvider.GetRequiredService<SettingsView>();

        Loaded += OnLoaded;
    }

    private async void OnLoaded(object sender, RoutedEventArgs e)
    {
        await _viewModel.LoadProfilesAsync();
    }

    // Expose the LogPanel RichTextBox (generated by x:Name="LogPanel") for LogPanelSink wiring
    public RichTextBox GetLogPanel() => LogPanel;
}
