using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using PersonalToolBox.Models;
using PersonalToolBox.Services;

namespace PersonalToolBox.ViewModels;

/// <summary>
/// 分类编辑窗口 ViewModel，管理添加/编辑分类的交互逻辑
/// </summary>
public partial class CategoryEditViewModel : ObservableObject
{
    private readonly IDataService _dataService;
    private readonly ILogService _logService;
    private readonly Category? _editingCategory;

    [ObservableProperty]
    private string _windowTitle = "添加分类";

    [ObservableProperty]
    private string _name = string.Empty;

    public Action<bool?>? CloseAction { get; set; }
    public bool Saved { get; private set; }

    public CategoryEditViewModel(IDataService dataService, ILogService logService, Category? categoryToEdit = null)
    {
        _dataService = dataService;
        _logService = logService;
        _editingCategory = categoryToEdit;

        if (categoryToEdit != null)
        {
            WindowTitle = "编辑分类";
            Name = categoryToEdit.Name;
        }
    }

    [RelayCommand]
    private void Save()
    {
        try
        {
            if (string.IsNullOrWhiteSpace(Name))
            {
                _logService.Warning("分类名称不能为空");
                return;
            }

            if (_editingCategory != null)
            {
                _editingCategory.Name = Name.Trim();
                _logService.Info($"已更新分类: {Name.Trim()}");
            }
            else
            {
                _dataService.Config.Categories.Add(new Category
                {
                    Id = Guid.NewGuid().ToString(),
                    Name = Name.Trim()
                });
                _logService.Info($"已添加分类: {Name.Trim()}");
            }

            _dataService.Save();
            Saved = true;
            CloseAction?.Invoke(true);
        }
        catch (Exception ex)
        {
            _logService.Error($"保存分类失败: {ex.Message}");
        }
    }

    [RelayCommand]
    private void Cancel()
    {
        CloseAction?.Invoke(false);
    }
}
