using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Blazored.Modal;
using Blazored.Modal.Services;
using DiplomovaPrace.Contracts.Orders.InputModels;
using DiplomovaPrace.Contracts.ProductCategories;
using DiplomovaPrace.Contracts.ProductCategories.ViewModels;
using DiplomovaPrace.Contracts.Products;
using DiplomovaPrace.Contracts.Products.ViewModels;
using Microsoft.AspNetCore.Components;

namespace DiplomovaPrace.Web.Admin.Pages.Orders.Modal
{
	public partial class AddOrderItemModal
	{
		[CascadingParameter]
		public BlazoredModalInstance ModalInstance { get; set; }

		[Parameter]
		public string ConfirmButtonText { get; set; }

		[Parameter]
		public string CancelButtonText { get; set; }

		[Inject]
		private IProductCategoryFacadeContract ProductCategoryFacadeContract { get; set; }

		[Inject]
		private IProductFacadeContract ProductFacadeContract { get; set; }

		private List<ProductDto> products = new();

		private List<ProductDto> filteredProducts = new();

		private List<ProductCategoryDto> productCategories = new();

		private OrderItemIM OrderItemIM { get; set; } = new();

		private int productCategoryID = -1;

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

			productCategories = await ProductCategoryFacadeContract.GetAllProductCategoriesAsync();
			products = await ProductFacadeContract.GetAllProductsAsync();

		}

		private void HandleProductCategoryChange()
		{
			if (productCategoryID > 0)
			{
				filteredProducts = products.Where(i => i.ProductCategoryID == productCategoryID).ToList();
				OrderItemIM = new();
				OrderItemIM.ProductID = -1;
			}
		}

		private void HandleProductSelectChange()
		{
			var product = products.Find(i => i.ID == OrderItemIM.ProductID);

			if (product is not null)
			{
				OrderItemIM.Name = product.Name;
				OrderItemIM.Price = product.Price;
				OrderItemIM.Amount = 1;
				OrderItemIM.TotalPrice = product.Price;
			}
		}

		private void SubmitForm()
		{
			ModalInstance.CloseAsync(ModalResult.Ok(OrderItemIM));
		}

		private void Cancel()
		{
			ModalInstance.CancelAsync();
		}
	}
}
