using LiteCharms.Features;
using LiteCharms.Features.MidrandBooks.Authors;
using LiteCharms.Features.MidrandBooks.Authors.Models;
using LiteCharms.Features.MidrandBooks.Payments;
using LiteCharms.Features.MidrandBooks.Payments.Models;
using LiteCharms.Features.MidrandBooks.Products;
using LiteCharms.Features.MidrandBooks.Products.Models;

namespace MidrandBookshop.Components.Pages;

public partial class ProductView : ComponentBase
{
    [Parameter] public long BookId { get; set; }

    [Inject] private ProductService ProductService { get; set; } = default!;
    [Inject] private AuthorService AuthorService { get; set; } = default!;
    [Inject] private NavigationManager Navigation { get; set; } = default!;
    [Inject] private CartService CartService { get; set; } = default!;

    protected Cart ShoppingCart => CartService?.ShoppingCart!;

    protected bool IsLoading { get; private set; } = true;
    protected Product? CurrentProduct { get; private set; }
    protected ProductPrice? CurrentPrice { get; private set; }
    protected decimal LivePrice { get; private set; } = 0.00m;
    protected string AuthorName { get; private set; } = "Unknown Author";
    protected string PrimaryCategory { get; private set; } = "General";

    protected string ActiveImageUrl { get; set; } = string.Empty;
    protected List<string> Thumbnails { get; private set; } = [];
    protected int Quantity { get; private set; } = 1;

    protected Author? CurrentAuthor { get; private set; }

    protected override async Task OnParametersSetAsync()
    {
        try
        {
            IsLoading = true;
            CurrentProduct = null;
            CurrentAuthor = null;
            Thumbnails.Clear();

            var productResult = await ProductService.GetProductAsync(BookId);

            if (productResult.IsSuccess && productResult.Value != null)
            {
                CurrentProduct = productResult.Value;
                AuthorName = CurrentProduct.Metadata?.Manufacturer ?? "Unknown Author";

                var priceResult = await ProductService.GetProductPriceAsync(BookId);
                LivePrice = priceResult.IsSuccess ? priceResult.Value.Amount : 0m;
                CurrentPrice = priceResult.IsSuccess ? priceResult.Value : null;

                var categoryResult = await ProductService.GetProductCategoriesAsync(BookId);
                if (categoryResult.IsSuccess && categoryResult.Value.Length > 0)
                    PrimaryCategory = categoryResult.Value[0].Name ?? "General";

                var authorResult = await AuthorService.GetAuthorByProductIdAsync(BookId);
                if (authorResult.IsSuccess && authorResult.Value != null)
                {
                    CurrentAuthor = authorResult.Value;

                    if (CurrentAuthor.PublisherType == PublisherTypes.Company && !string.IsNullOrWhiteSpace(CurrentAuthor.Company))
                        AuthorName = CurrentAuthor.Company;
                    else
                        AuthorName = $"{CurrentAuthor.Name} {CurrentAuthor.LastName}".Trim();
                }

                if (!string.IsNullOrWhiteSpace(CurrentProduct.ImageUrl))
                    Thumbnails.Add(CurrentProduct.ImageUrl);

                if (CurrentProduct.ThumbnailUrls != null && CurrentProduct.ThumbnailUrls?.Length != 0)
                    foreach (var url in CurrentProduct.ThumbnailUrls!)
                        if (!string.IsNullOrWhiteSpace(url) && !Thumbnails.Contains(url)) Thumbnails.Add(url);

                ActiveImageUrl = Thumbnails.FirstOrDefault() ?? string.Empty;
            }
        }
        catch (Exception)
        {
            CurrentProduct = null;
            CurrentPrice = null;
        }
        finally
        {
            IsLoading = false;
        }
    }

    protected async void IncreaseQty()
    {
        if (CurrentPrice is not null)
        {
            CartService.UpdateQuantity(CurrentPrice!.Id, 1);
                        
            Quantity = CartService.GetCartItemQuantity(ShoppingCart, CurrentPrice.Id);

            await CartService.SaveCartToStorageAsync();
        }
    }
    protected async void DecreaseQty() 
    {
        if (Quantity >= 1)
        {
            CartService.UpdateQuantity(CurrentPrice!.Id, -1);

            Quantity = CartService.GetCartItemQuantity(ShoppingCart, CurrentPrice.Id);

            await CartService.SaveCartToStorageAsync();
        }
    }

    protected async void HandleAddToCart()
    {
        if (CurrentProduct == null) return;

        if (CurrentPrice is not null)
        {
            if(ShoppingCart.Items.Any(p => p.Price!.Id == CurrentPrice.Id))
            {
                CartService.UpdateQuantity(CurrentPrice.Id, 1);

                await CartService.SaveCartToStorageAsync();

                return;
            }

            CartService.AddItem(CurrentPrice, CurrentProduct, CurrentAuthor!);

            Quantity = CartService.GetCartItemQuantity(ShoppingCart, CurrentPrice.Id);

            await CartService.SaveCartToStorageAsync();
        }
    }

    protected void ViewAllAuthorBooks()
    {
        if (CurrentAuthor is not null)
            Navigation.NavigateTo($"/?authorId={CurrentAuthor.Id}");
    }
}