using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Dollet.Core.Abstractions;
using Dollet.Core.Abstractions.DomainServices;
using Dollet.Core.Entities;
using Dollet.Helpers;
using Dollet.Pages;

namespace Dollet.ViewModels.Accounts
{
    public partial class AddAccountPageViewModel(IAccountDomainService accountService, IUnitOfWork unitOfWork) : ObservableObject
    {
        private readonly IAccountDomainService _accountService = accountService;
        private readonly IUnitOfWork _unitOfWork = unitOfWork;

        [ObservableProperty]
        ObservableRangeCollection<string> _icons = [], _colors = [], _currencies = [];

        [ObservableProperty]
        decimal? _amount;

        [ObservableProperty]
        [NotifyCanExecuteChangedFor(nameof(AddAccountCommand))]
        string _name, _selectedIcon, _selectedColor, _selectedCurrency;
        
        [ObservableProperty]
        string _description = string.Empty;
        
        [ObservableProperty]
        bool _isHidden, _isDefault;

        [RelayCommand]
        async Task Appearing()
        {
            Icons.ReplaceRange(Defined.Icons);
            Colors.ReplaceRange(Defined.Colors);

            var currencies = await _unitOfWork.CurrencyRepository.GetAllAsync();
            Currencies.ReplaceRange(currencies.Select(x => x.Code).ToList());

            SelectedCurrency = currencies.FirstOrDefault(x => x.IsDefault)?.Code;
            IsDefault = !await _unitOfWork.AccountRepository.ExistsAsync();
        }

        [RelayCommand(CanExecute = nameof(CanAddAccount))]
        async Task AddAccount()
        {
            var added = await _accountService.CreateAsync(new Account
            {
                Amount = Amount ?? 0,
                Description = Description,
                Name = Name,
                Icon = SelectedIcon,
                Color = SelectedColor,
                Currency = SelectedCurrency,
                IsHidden = IsHidden
            }, IsDefault);

            if (added)
            {
                await Shell.Current.GoToAsync($"//{nameof(AccountsPage)}");
            }
        }

        bool CanAddAccount() =>
            !string.IsNullOrWhiteSpace(Name) &&
            !string.IsNullOrWhiteSpace(SelectedIcon) &&
            !string.IsNullOrWhiteSpace(SelectedColor) &&
            !string.IsNullOrWhiteSpace(SelectedCurrency);
    }
}