using CommunityToolkit.Maui.Alerts;
using CommunityToolkit.Maui.Core;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Dollet.Core.Abstractions;
using Dollet.Core.Entities;
using Dollet.Helpers;

namespace Dollet.ViewModels.Transactions.Expenses
{
    public partial class AddExpensePageViewModel(IUnitOfWork unitOfWork) : ObservableObject
    {
        private readonly IUnitOfWork _unitOfWork = unitOfWork;

        [ObservableProperty]
        private Account _selectedAccount;
        public decimal Amount { get; set; }
        public Category SelectedCategory { get; set; }
        public DateTime Date { get; set; }
        public string Comment { get; set; }
        public DateTime MaximumDate { get; } = DateTime.Now;

        public ObservableRangeCollection<Account> Accounts { get; } = [];
        public ObservableRangeCollection<Category> Categories { get; } = [];

        [RelayCommand]
        async Task Appearing()
        {
            var accounts = await _unitOfWork.AccountRepository.GetAllAsync();
            var categories = await _unitOfWork.CategoryRepository.GetAllAsync();

            Accounts.ReplaceRange(accounts);
            Categories.ReplaceRange(categories);

            SelectedAccount = accounts.FirstOrDefault(x => x.IsDefault);
        }

        [RelayCommand]
        async Task AddExpense()
        {
            var selectedAccount = Accounts.FirstOrDefault(x => x.Id == SelectedAccount.Id);

            selectedAccount.Amount -= Amount;

            _unitOfWork.AccountRepository.Update(selectedAccount);
            _unitOfWork.ExpensesRepository.Add(new Expense
            {
                Amount = Amount,
                AccountId = SelectedAccount.Id,
                CategoryId = SelectedCategory.Id,
                Date = Date,
                Comment = Comment
            });
            await _unitOfWork.CommitAsync();

            await Toast
                .Make("Added", ToastDuration.Long)
                .Show();

            await Shell.Current.GoToAsync("..");
        }
    }
}
