using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Scry.Core.Models;
using Scry.Models;
using Scry.Services;
using Scry.Views;
using System.Collections.ObjectModel;

namespace Scry.ViewModels;

public partial class CollectionViewModel : ObservableObject
{
    private readonly ICardRepository _cardRepository;

    [ObservableProperty]
    private ObservableCollection<CollectionEntry> _entries = [];

    [ObservableProperty]
    private int _totalCards;

    [ObservableProperty]
    private int _uniqueCards;

    [ObservableProperty]
    private bool _isEmpty = true;

    public CollectionViewModel(ICardRepository cardRepository)
    {
        _cardRepository = cardRepository;
    }

    [RelayCommand]
    private void LoadCollection()
    {
        var allEntries = _cardRepository.GetAll();
        Entries = new ObservableCollection<CollectionEntry>(allEntries.OrderByDescending(e => e.AddedAt));
        TotalCards = _cardRepository.TotalCards;
        UniqueCards = _cardRepository.UniqueCards;
        IsEmpty = Entries.Count == 0;
    }

    [RelayCommand]
    private async Task ViewCardAsync(CollectionEntry entry)
    {
        await Shell.Current.GoToAsync($"{nameof(CardDetailPage)}?entryId={entry.Id}");
    }

    [RelayCommand]
    private void IncrementQuantity(CollectionEntry entry)
    {
        _cardRepository.UpdateQuantity(entry.Id, entry.Quantity + 1);
        LoadCollection();
    }

    [RelayCommand]
    private void DecrementQuantity(CollectionEntry entry)
    {
        if (entry.Quantity > 1)
        {
            _cardRepository.UpdateQuantity(entry.Id, entry.Quantity - 1);
        }
        else
        {
            _cardRepository.Remove(entry.Id);
        }
        LoadCollection();
    }

    [RelayCommand]
    private async Task RemoveEntryAsync(CollectionEntry entry)
    {
        var result = await Shell.Current.DisplayAlertAsync(
            "Remove Card",
            $"Remove all {entry.Quantity}x {entry.Card.Name} from collection?",
            "Remove",
            "Cancel");

        if (result)
        {
            _cardRepository.Remove(entry.Id);
            LoadCollection();
        }
    }
}
