using System;
using System.Collections.Generic;
using System.Diagnostics;
using AvaloniaSideBarEx.Models;
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<MenuItemModel> MenuItems { get; } = [
        new() { Label = "首頁"},
        new() { Label = "設定"},
        new() { Label = "關於"}
    ];
    
    [ObservableProperty]
    private MenuItemModel? _selectedMenuItem;
    
    [ObservableProperty]
    private ObservableObject? _currentPage = services.GetRequiredService<HomeViewModel>();
    
    // 這是 CommunityToolkit 自動生成的鉤子方法 (Hook)
    // 當 _selectedMenuItem 改變時，這個函數會被自動呼叫
    partial void OnSelectedMenuItemChanged(MenuItemModel? value)
    {
        if (value == null) return;
    
        // 現在你可以直接拿到 Label 了
        Navigate(value.Label); 
    
        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>()
        };
    }
}