import $ from "jquery";

export function universalHandler(config) {
  const {
    selectSelector,
    repeaterSelector,
    inputName,
    containerSelector,
    removeButtonSelector,
  } = config;

  $(document).on("select2:select", selectSelector, function (e) {
    const select = $(this);
    const selectedOption = e.params.data;
    const productId = String(selectedOption.id);
    const productName = selectedOption.text;
    const removeButtonText = $(".firevert-form").data("remove-button-text");

    if (productId && productName && productName !== "Select product") {
      const escapedInputName = inputName
        .replace(/\[/g, "\\[")
        .replace(/\]/g, "\\]");
      const existingInputs = $(
        `${repeaterSelector} input[name='${escapedInputName}']`
      );
      let productExists = false;

      existingInputs.each(function () {
        if (String($(this).val()) === productId) {
          productExists = true;
          return false;
        }
      });

      if (!productExists) {
        const repeaterItem = `
            <div class="repeater-item" style="margin-bottom: 5px; display: flex; align-items: center; gap: 10px;">
              <input type="hidden" name="${inputName}" value="${productId}" />
              <span class="product-name">${productName}</span>
              <button type="button" class="button ${removeButtonSelector.replace(
                ".",
                ""
              )}">${removeButtonText}</button>
            </div>
          `;

        $(containerSelector).before(repeaterItem);
        select.val(null).trigger("change");
      } else {
        alert($(".firevert-form").data("product-exists-message"));
        select.val(null).trigger("change");
      }
    }
  });

  $(document).on("click", removeButtonSelector, function () {
    $(this).closest(".repeater-item").remove();
  });
}
