using System;
using System.Collections.Generic;
using System.Diagnostics;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.DependencyInjection;

namespace AvaloniaSideBarEx.ViewModels;

public partial class MainWindowViewModel(IServiceProvider services) : ViewModelBase
{
    //側邊欄控制
    [ObservableProperty]
    private bool _isSidebarOpen;
    
    [RelayCommand]
    private void ToggleSidebar()
    {
        IsSidebarOpen = !IsSidebarOpen;
    }
    
    //側邊欄導航
    private HomeViewModel? _homeViewModel;
    private SettingsViewModel? _settingsViewModel;
    private AboutViewModel? _aboutViewModel;
    public List<string> MenuItems { get; } = ["首頁", "設定", "關於"];
    
    [ObservableProperty]
    private string? _selectedMenuItem = "首頁";
    
    [ObservableProperty]
    private ObservableObject? _currentPage = services.GetRequiredService<HomeViewModel>();
    
    // 這是 CommunityToolkit 自動生成的鉤子方法 (Hook)
    // 當 _selectedMenuItem 改變時，這個函數會被自動呼叫
    partial void OnSelectedMenuItemChanged(string? value)
    {
        // 直接在這裡呼叫你的導航邏輯
        OnMenuSelected();
    }
    
    [RelayCommand]
    private void OnMenuSelected()
    {
        //Debug.WriteLine($"當前選中：{SelectedMenuItem}");
        Navigate(SelectedMenuItem);
        if (IsSidebarOpen)
        {
            IsSidebarOpen = false;
        }
    }
    
    private void Navigate(string? target)
    {
        //根據選中的菜單名稱，實例化對應的 ViewModel
        CurrentPage = target switch
        {
            "首頁" => _homeViewModel ??= services.GetRequiredService<HomeViewModel>(), // 如果 _homeViewModel 是 null，則創建新的並賦值
            "設定" => _settingsViewModel ??= services.GetRequiredService<SettingsViewModel>(),
            "關於" => _aboutViewModel ??= services.GetRequiredService<AboutViewModel>(),
            _ => _homeViewModel ??= services.GetRequiredService<HomeViewModel>()
        };
    }
}