using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace OTSSignsOrchestrator.Desktop.ViewModels;

public partial class MainWindowViewModel : ObservableObject
{
    private readonly IServiceProvider _services;

    [ObservableProperty]
    private ObservableObject? _currentView;

    [ObservableProperty]
    private string _selectedNav = "Hosts";

    [ObservableProperty]
    private string _statusMessage = "Ready";

    public ObservableCollection<string> NavItems { get; } = new()
    {
        "Hosts",
        "Instances",
        "Create Instance",
        "Secrets",
        "Settings",
        "Logs"
    };

    public MainWindowViewModel(IServiceProvider services)
    {
        _services = services;
        NavigateTo("Hosts");
    }

    partial void OnSelectedNavChanged(string value)
    {
        NavigateTo(value);
    }

    [RelayCommand]
    private void NavigateTo(string page)
    {
        CurrentView = page switch
        {
            "Hosts" => (ObservableObject)_services.GetService(typeof(HostsViewModel))!,
            "Instances" => (ObservableObject)_services.GetService(typeof(InstancesViewModel))!,
            "Create Instance" => (ObservableObject)_services.GetService(typeof(CreateInstanceViewModel))!,
            "Secrets" => (ObservableObject)_services.GetService(typeof(SecretsViewModel))!,
            "Settings" => (ObservableObject)_services.GetService(typeof(SettingsViewModel))!,
            "Logs" => (ObservableObject)_services.GetService(typeof(LogsViewModel))!,
            _ => CurrentView
        };
    }

    /// <summary>
    /// Navigates to the Instances page and auto-selects the instance with the given abbreviation
    /// once the live refresh completes.
    /// </summary>
    public void NavigateToInstancesWithSelection(string abbrev)
    {
        SelectedNav = "Instances"; // triggers OnSelectedNavChanged → NavigateTo("Instances")
        if (CurrentView is InstancesViewModel instancesVm)
            instancesVm.SetPendingSelection(abbrev);
    }

    public void SetStatus(string message)
    {
        StatusMessage = message;
    }
}
