import { InobyModule } from "@lib/inoby-module";
import * as $ from "jquery";

class ProductArchiveModule extends InobyModule {
  run() {

    $(document.body).on("focusin change input", "form.cart input.qty", function (e) {
      e.preventDefault();
      var $self = $(this);
      var max = $self.attr('max') === 'INF' ? Number.POSITIVE_INFINITY : parseInt($self.attr("max"));
      var min = parseInt($self.attr('min'));
      var value = parseInt($self.val() as string);
      const normalPrice = $(this).parents('.quick-cart').find('.normal-price bdi').text();
      const normalPriceScreenReader = $(this).parents('.quick-cart').find('.normal-price .screen-reader-text').text();
      const b2bPrice = $(this).parents('.quick-cart').find('.b2b-price bdi').text();
      const b2bPriceScreenReader = $(this).parents('.quick-cart').find('.b2b-price .screen-reader-text').text();

      if(value < min){
        $self.val(min);
      }
      if(value > max){
        $self.val(max);
      }
      
      if(!isNaN(value) && value != 0){
        value = parseInt($self.val() as string);
          var normalPriceNumber = normalPrice.replace(window.inoby_vars.currency?.symbol || '€', '').trim();
          var normalCurrencySymbol = normalPrice.replace(normalPriceNumber, '').trim();
          $(this).parents('.quick-cart').find('.normal-price bdi').text((parseFloat(normalPriceScreenReader) * value).toFixed(2) + normalCurrencySymbol);
      
          var b2bPriceNumber = b2bPrice.replace(window.inoby_vars.currency?.symbol || '€', '').trim();
          var b2bCurrencySymbol = b2bPrice.replace(b2bPriceNumber, '').trim();
          $(this).parents('.quick-cart').find('.b2b-price bdi').text((parseFloat(b2bPriceScreenReader) * value).toFixed(2) + b2bCurrencySymbol);
      }
      
    });

    $(document.body).on("focusin change input", "form.cart-variations input.qty", function (e) {
      e.preventDefault();
      var $self = $(this);
      var max = $self.attr('max') === 'INF' ? Number.POSITIVE_INFINITY : parseInt($self.attr("max"));
      var min = parseInt($self.attr('min'));
      var inputVariationId = $self.attr('name').replace('quantity-', '');
      var value = parseInt($self.val() as string);

      if(isNaN(max)){
        $self.val(0);
      }
      if(value < min){
        $self.val(min);
      }
      if(value > max){
        $self.val(max);
      }
      
      if(!isNaN(value)){
        value = parseInt($self.val() as string);
        var $addToCartWrapper = $self.parents('.cart-variations').find('.items-end');
        $addToCartWrapper.find('input[name="quantity-'+ inputVariationId +'"]').val(value);
        summarizeTotal(this);
      }
      
    });

    function getFormData($form: any) {
    return $form.serializeArray().reduce(function (acc: any, obj: any) {
      acc[obj.name] = obj.value;
      return acc;
    }, {});
  };

    $(document).on("click", ".add-to-cart-variations-button", function (e) {
      e.preventDefault();
      e.stopPropagation();

      var $self = $(this);
      var $form = $self.closest("form");
      var data = getFormData($form);
      
      // Add nonce for security
      data._wpnonce = window.inoby_vars.ajax.nonce;
      
      // Validate required fields
      if (!data.product_id) {
        alert('Product ID is required');
        return;
      }
      
      // Check if at least one variation is selected
      var hasVariations = false;
      for (var key in data) {
        if (key.startsWith('variation_id-') && data[key]) {
          hasVariations = true;
          break;
        }
      }
      
      if (!hasVariations) {
        alert('Please select at least one variation');
        return;
      }
      
      $('#inoby-preloader').removeClass("loaded hidden");
      $('#inoby-preloader').css('opacity', 0.5);
      
      $.ajax({
        type: "POST",
        url: window.inoby_vars.ajax.url + '/?rc-ajax=add_to_cart_variables',
        data: data,
        dataType: "json",
        success: function (response) {
          if (response.success) {
            // Open minicart if requested
            $('#cart-wrapper .content').load(' #cart-wrapper .content > *', function(){
              if (response.data.open_minicart && $('#cart-wrapper').length) {
                if($('#cart-wrapper.popup').length){
                  $('#cart-wrapper').addClass('active');
                } 
              }
              // Hide any loading indicators
              $('#inoby-preloader').addClass("loaded hidden");
              $('#inoby-preloader').css('opacity', 0);
            });
          } 
        },
        error: function (xhr, status, error) {
          console.error('AJAX Error:', error);
          // Hide any loading indicators
              $('#inoby-preloader').addClass("loaded hidden");
              $('#inoby-preloader').css('opacity', 0);
        },
      });
    });

    $(document).on('click', '.add-to-cart-wrapper .content-product-button', function(e){
      e.preventDefault();
      summarizeTotal(this);
      if($(this).hasClass('active')){
        $(this).removeClass('active');
        $(this).parents('.b2b-product-card').find('.variable-details').slideUp();
      } else {
        $(this).addClass('active');
        $(this).parents('.b2b-product-card').find('.variable-details').slideDown();
      }
    });

    function summarizeTotal(element: HTMLElement){
      var $b2bCard = $(element).parents('.b2b-product-card');
      var quantity = 0;
      var normalPrice = 0;
      var b2bPrice = 0;
      $b2bCard.find('.variation').each(function(index, element){
        var elementQuantity = parseInt($(element).find('.input-text.qty').val() as string)
        quantity = quantity + elementQuantity;
        var totalElementPrice = elementQuantity * parseFloat($(element).find('.normalPrice').text().replace(window.inoby_vars.currency?.symbol || '€', '').trim());
        var totalElementB2BPrice = elementQuantity * parseFloat($(element).find('.b2bPrice bdi').text().replace(window.inoby_vars.currency?.symbol || '€', '').replace(',', '.').trim());
        normalPrice = normalPrice + totalElementPrice;
        b2bPrice = b2bPrice + totalElementB2BPrice;
      });
      $b2bCard.find('.summary-quantity .quantity-text').text(quantity);
      $b2bCard.find('.summary-normalPrice .normalPrice-value').text(normalPrice.toFixed(2));
      $b2bCard.find('.summary-b2bPrice .b2bPrice-value').text(b2bPrice.toFixed(2));
    }
  }
}

new ProductArchiveModule().runOnReady();
