using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using System;
using System.Threading.Tasks;
using TodoList.Models;
using TodoList.Services;

namespace TodoList.ViewModels
{
    public partial class QuickEntryViewModel : ObservableObject
    {
        private readonly IDataService _dataService;
        private Action _closeAction;

        [ObservableProperty]
        private string content;

        [ObservableProperty]
        private TodoPriority priority = TodoPriority.Medium;

        public QuickEntryViewModel(IDataService dataService, Action closeAction)
        {
            _dataService = dataService;
            _closeAction = closeAction;
        }

        [RelayCommand]
        private async Task SaveAsync()
        {
            if (string.IsNullOrWhiteSpace(Content)) return;

            var newTask = new TodoItem
            {
                Content = Content,
                Priority = Priority,
                IsCompleted = false,
                SyncStatus = SyncStatus.Pending
            };

            await _dataService.SaveTaskAsync(newTask);
            
            // Notify MainViewModel
            WeakReferenceMessenger.Default.Send(new TaskAddedMessage());

            // Reset and close
            Content = string.Empty;
            Priority = TodoPriority.Medium;
            _closeAction?.Invoke();
        }

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