using System;
using System.Linq;
using System.Threading.Tasks;
using DiplomovaPrace.Contracts;
using DiplomovaPrace.Contracts.Orders;
using DiplomovaPrace.Contracts.Orders.ViewModels;
using DiplomovaPrace.Web.Admin.Services;
using DiplomovaPrace.Web.Admin.Store.DeliveryTypeUseCase;
using DiplomovaPrace.Web.Admin.Store.OrderStateUseCase;
using DiplomovaPrace.Web.Admin.Store.PaymentStateUseCase;
using DiplomovaPrace.Web.Admin.Store.PaymentTypeUseCase;
using Fluxor;
using Microsoft.AspNetCore.Components;

namespace DiplomovaPrace.Web.Admin.Pages.Orders
{
	public partial class OrderDetail
	{
		[Parameter]
		public int OrderID { get; set; }

		[Inject]
		private IOrderFacadeContract OrderFacadeContract { get; set; }

		[Inject]
		private IState<DeliveryTypeState> DeliveryTypeState { get; set; }

		[Inject]
		private IState<OrderState> OrderState { get; set; }

		[Inject]
		private IState<PaymentState> PaymentState { get; set; }

		[Inject]
		private IState<PaymentTypeState> PaymentTypeState { get; set; }

		[Inject]
		private IOrderService OrderService { get; set; }

		private OrderDetailVM order;

		protected override async Task OnInitializedAsync()
		{
			await base.OnInitializedAsync().ConfigureAwait(false);

			await LoadAllOrderPropertiesAsync().ConfigureAwait(false);
			order = await OrderFacadeContract.GetOrderDetailByIDAsync(ValueDto.FromValue(OrderID)).ConfigureAwait(false);
		}

		private async Task LoadAllOrderPropertiesAsync()
		{
			if (DeliveryTypeState.Value.DeliveryTypes is null ||
				OrderState.Value.OrderStates is null ||
				PaymentState.Value.PaymentStates is null ||
				PaymentTypeState.Value.PaymentTypes is null)
			{
				await OrderService.RequestOrderPropertiesAsync().ConfigureAwait(false);
			}
		}

		private string GetDeliveryTypeNameAndFee()
		{
			var deliveryType = DeliveryTypeState.Value.DeliveryTypes.Find(i => i.ID == order.DeliveryTypeID);

			return CalculateOrderItemsPrice() >= 1000
				? $"<span>{deliveryType?.Name}: + {deliveryType?.Fee} Kč</span><br /><span>{deliveryType?.Name}: - {deliveryType?.Fee} Kč</span>"
				: $"<span>{deliveryType?.Name}: + {deliveryType?.Fee}</span>";
		}

		private string GetPaymentTypeNameAndFee()
		{
			var paymentType = PaymentTypeState.Value.PaymentTypes.Find(i => i.ID == order.PaymentTypeID);

			return $"{paymentType?.Name}: + {paymentType?.Fee}";
		}

		private decimal CalculateOrderItemsPrice()
		{
			return Decimal.Round(order.OrderItems.Sum(i => i.Amount * i.Price), 2, MidpointRounding.AwayFromZero);
		}
	}
}
