using Microsoft.AspNetCore.Mvc;
using Nop.Core;
using Nop.Core.Domain.Catalog;
using Nop.Plugin.Misc.AuctionPlugin.Domains.Entities;
using Nop.Plugin.Misc.AuctionPlugin.Models;
using Nop.Plugin.Misc.AuctionPlugin.Services;
using Nop.Services.Catalog;
using Nop.Services.Logging;
using Nop.Web.Framework.Controllers;
using Nop.Web.Models.Catalog;

namespace Nop.Plugin.Misc.AuctionPlugin.Controllers;

public class AuctionController(AuctionService auctionService, ILogger logger, IProductService productService, MyProductModelFactory productModelFactory, IWorkContext _workContext)
	: BasePluginController
{
	// GET
    public IActionResult Index()
    {
        //var a = new Auction();
        return View();
    }

    [HttpPost]
    public async Task<IActionResult> PlaceBid([FromBody] AuctionBid model)
    {

        await logger.InformationAsync("PlaceBid called");

        //if (model.BidPrice < CurrentPrice + LicitStep) 
        //{
        //    return BadRequest("Bid price is too low.");
        //}

        // kéne valami visszajelzés
        await auctionService.InsertBidAsync(model);
        var bidSuccess = true;
        if (bidSuccess)
        {
            return Ok(new { message = "Your bid was successfully placed!" });
        }
        else
        {
            return BadRequest("Failed to place bid. Please try again.");
        }
    }

    [HttpPost]
    public async Task<IActionResult> RefreshAuctionWidget([FromBody] RefreshWidgetRequest request)
    {
        //await logger.InformationAsync($"Refresh auction widget called from {request.WidgetZone} with data of {request.ProductId}");

        var product = await productService.GetProductByIdAsync(request.ProductId);
        var detailsModel = await productModelFactory.PrepareProductDetailsModelAsync(product);

        return ViewComponent("AuctionPublic", new { widgetZone = request.WidgetZone, additionalData = detailsModel });
    }

    public async Task<IActionResult> LiveScreen(int auctionId)
    {
        var auctionDto = await auctionService.GetAuctionDtoWithAuctionBids(auctionId, true, 5); //A javascript-ben az első 6-ot vágod le, melyik a valid? - J.
        var activeMapping = auctionDto?.ProductToAuctionDtos.MinBy(x => x.SortIndex);
        var isAnyItemLive = activeMapping != null;
        var myUser = await _workContext.GetCurrentCustomerAsync();
        if (auctionDto == null || myUser == null)
        {
            return new RedirectResult("/", false);
        }
        
        var model = new LiveScreenViewModel(auctionDto);
        Product product;
        ProductDetailsModel productDetailsModel;
        
        int activeProductId;
        int activeProductToAuctionId;
        decimal basePrice = 0;
        decimal currentPrice = 0;
        decimal nextStep = 0;

        if (isAnyItemLive) 
        { 
            product = await productService.GetProductByIdAsync(activeMapping.ProductId);
            activeProductId = activeMapping.ProductId;
            activeProductToAuctionId = activeMapping.Id;
            productDetailsModel = await productModelFactory.PrepareProductDetailsModelAsync(product);            
            basePrice = activeMapping.StartingPrice;
            currentPrice = activeMapping.CurrentPrice;
            nextStep = AuctionService.GetStepAmount(currentPrice);
        }
        else
        {
            activeMapping = null;
            product = null;
            activeProductId = 0;
            activeProductToAuctionId = 0;
            productDetailsModel = null;
        }

        //I need product data
        //create a more detailed model

        
        model.IsAnyItemActive = isAnyItemLive;
        model.AuctionId = auctionId;
        model.CurrentProductToAuction = activeMapping;
        model.ActiveProductId = activeProductId;
        model.ActiveProductToAuctionId = activeProductToAuctionId;        
        model.ActiveProductDetails = productDetailsModel;
        model.BasePrice = basePrice;
        model.CurrentPrice = currentPrice;
        model.LicitStep = nextStep;
        model.BasePrice = basePrice;
        model.CurrentPrice = currentPrice;
        model.UserCustomerId = myUser.Id;        


        return View("~/Plugins/Misc.AuctionPlugin/Views/LiveScreen.cshtml", model);
    }
}