using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Scry.Core.Models;
using Scry.Models;
using Scry.Services;

namespace Scry.ViewModels;

[QueryProperty(nameof(CardId), "cardId")]
[QueryProperty(nameof(EntryId), "entryId")]
public partial class CardDetailViewModel : ObservableObject
{
    private readonly ICardRepository _cardRepository;

    [ObservableProperty]
    private Card? _card;

    [ObservableProperty]
    private CollectionEntry? _entry;

    [ObservableProperty]
    private bool _isInCollection;

    [ObservableProperty]
    private string? _cardId;

    [ObservableProperty]
    private string? _entryId;

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

    partial void OnEntryIdChanged(string? value)
    {
        if (string.IsNullOrEmpty(value)) return;

        Entry = _cardRepository.GetById(value);
        if (Entry != null)
        {
            Card = Entry.Card;
            IsInCollection = true;
        }
    }

    partial void OnCardIdChanged(string? value)
    {
        if (string.IsNullOrEmpty(value)) return;

        // For now, find by looking through collection
        var entries = _cardRepository.GetAll();
        Entry = entries.FirstOrDefault(e => e.Card.Id == value);
        if (Entry != null)
        {
            Card = Entry.Card;
            IsInCollection = true;
        }
    }

    [RelayCommand]
    private void IncrementQuantity()
    {
        if (Entry == null) return;
        _cardRepository.UpdateQuantity(Entry.Id, Entry.Quantity + 1);
        Entry = _cardRepository.GetById(Entry.Id);
    }

    [RelayCommand]
    private void DecrementQuantity()
    {
        if (Entry == null) return;

        if (Entry.Quantity > 1)
        {
            _cardRepository.UpdateQuantity(Entry.Id, Entry.Quantity - 1);
            Entry = _cardRepository.GetById(Entry.Id);
        }
    }

    [RelayCommand]
    private async Task GoBackAsync()
    {
        await Shell.Current.GoToAsync("..");
    }
}
