using Blazored.LocalStorage;
using drinkMe.Client.Models;
using drinkMe.Client.Services.Interfaces;
using drinkMe.Shared;
using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace drinkMe.Client.Pages
{
	public partial class Payment : ComponentBase
	{
		[Inject] ILocalStorageService LocalStorage { get; set; }
		[Inject] IPriceService PriceService { get; set; }
		[Inject] IPaymentService PaymentService { get; set; }
		[Inject] NavigationManager Navigation { get; set; }
		protected List<DrinkViewModel> CartDrinks { get; set; } = new List<DrinkViewModel>();
		protected List<DiscountCodeViewModel> DiscountCodes { get; set; } = new List<DiscountCodeViewModel>();
		protected CreditCardForm CreditCardForm { get; set; } = new CreditCardForm();
		protected PaymentMethod PaymentMethod { get; set; } = PaymentMethod.Undefined;
		protected float TotalPrice { get; set; }
		protected string PaymentError { get; set; }

		protected override async Task OnInitializedAsync()
		{
			CartDrinks = await LocalStorage.GetItemAsync<List<DrinkViewModel>>(nameof(CartDrinks));
			DiscountCodes = await LocalStorage.GetItemAsync<List<DiscountCodeViewModel>>(nameof(DiscountCodes)) ?? new List<DiscountCodeViewModel>();

			TotalPrice = PriceService.GetTotalPrice(DiscountCodes, CartDrinks);
			if (TotalPrice > 10f)
				PaymentMethod = PaymentMethod.CreditCard;
		}

		protected async Task Pay()
		{
			PaymentError = default;
			var paymentCart = new PurchaseCart();
			paymentCart.Discounts = DiscountCodes;
			paymentCart.PurchasingItems = CartDrinks.Select(cd => new CartItem
			{
				Id = cd.Id,
				Quantity = cd.Quantity
			}).ToList();
			paymentCart.IsPayedWithCash = PaymentMethod == PaymentMethod.Cash;
			if (!paymentCart.IsPayedWithCash)
			{
				paymentCart.CreditCardNumber = CreditCardForm.Number;
				paymentCart.CreditCardExpirationMonth = CreditCardForm.ExpirationMonth;
				paymentCart.CreditCardExpirationYear = CreditCardForm.ExpirationYear;
				paymentCart.CreditCardCVVCode = CreditCardForm.CVVCode;
			}
			var paymentResult = await PaymentService.Pay(paymentCart);

			if (!paymentResult.IsValid)
			{
				PaymentError = paymentResult.ErrorMessage;
				return;
			}

			await LocalStorage.RemoveItemAsync(nameof(CartDrinks));
			await LocalStorage.RemoveItemAsync(nameof(DiscountCodes));

			Navigation.NavigateTo("done");
		}

	}
}
