/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/* eslint-env browser */

function getCurrentProductOptionsPricing() {
  let selector = '';

  document.querySelectorAll('#sylius-product-adding-to-cart select[data-option]').forEach((element) => {
    const select = element;
    const option = select[select.selectedIndex].value;
    selector += `[data-${select.getAttribute('data-option')}="${option}"]`;
  });

  document.querySelectorAll('#sylius-product-adding-to-cart [data-option] input[type="radio"]:checked').forEach((element) => {
    const { option } = element.closest('[data-option]').dataset;
    selector += `[data-${option}="${element.value}"]`;
  });

  return document.querySelector('#sylius-variants-pricing').querySelector(selector);
}

function getCurrentProductOptionsTracked() {
  let selector = '';

  document.querySelectorAll('#sylius-product-adding-to-cart select[data-option]').forEach((element) => {
    const select = element;
    const option = select[select.selectedIndex].value;
    selector += `[data-${select.getAttribute('data-option')}="${option}"]`;
  });

  document.querySelectorAll('#sylius-product-adding-to-cart [data-option] input[type="radio"]:checked').forEach((element) => {
    const { option } = element.closest('[data-option]').dataset;
    selector += `[data-${option}="${element.value}"]`;
  });

  return document.querySelector('#sylius-variants-tracked').querySelector(selector);
}

function displayProductOptionsStock(price, isTracked) {
  const addToCartForm = document.querySelector('form#sylius-product-adding-to-cart');
  const outOfStockBlock = document.querySelector('#product-option-out-of-stock');
  const isInStockBlock = document.querySelector('#product-option-stock-tracked');
  const priceContainer = document.querySelector('.product-show-price');

  if (price) {
    priceContainer.innerHTML = price.innerHTML;
    addToCartForm.querySelector('button.btn-add-cart').style.display = 'inline-flex';
    outOfStockBlock.classList.add('d-none');

    if (isTracked.getAttribute('data-is-tracked')) {
      isInStockBlock.classList.remove('d-none');
    } else {
      isInStockBlock.classList.add('d-none');
    }
  } else {
    priceContainer.innerHTML = document.querySelector('#sylius-variants-pricing').getAttribute('data-unavailable-text');
    addToCartForm.querySelector('button.btn-add-cart').style.display = 'none';
    outOfStockBlock.classList.remove('d-none');
    isInStockBlock.classList.add('d-none');
  }
}

function displayFirstAvailableVariant() {
  const variantPricing = document.querySelector('#sylius-variants-pricing');
  const sizeSelect = document.querySelector('#sylius_add_to_cart_cartItem_variant_TAILLE');
  const colorSelect = document.querySelector('#sylius_add_to_cart_cartItem_variant_COULEUR');

  const firstAvailableVariant = variantPricing.firstElementChild;

  if (firstAvailableVariant === null) {
    return;
  }

  const size = firstAvailableVariant.getAttribute('data-taille');
  const color = firstAvailableVariant.getAttribute('data-couleur');

  if (sizeSelect) {
    sizeSelect.value = size;
  }
  if (colorSelect) {
    colorSelect.value = color;
  }
}

const handleProductOptionsChange = function handleProductOptionsChange() {
  document.querySelectorAll('[name*="sylius_add_to_cart[cartItem][variant]"]').forEach((item) => {
    item.addEventListener('change', () => {
      displayProductOptionsStock(getCurrentProductOptionsPricing(), getCurrentProductOptionsTracked());
    });

    displayProductOptionsStock(getCurrentProductOptionsPricing(), getCurrentProductOptionsTracked());
  });
};

const handleProductVariantsChange = function handleProductVariantsChange() {
  document.querySelectorAll('[name="sylius_add_to_cart[cartItem][variant]"]').forEach((item) => {
    item.addEventListener('change', () => {
      const selector = `[data-variant-code="${item.value}"]`;
      const price = document.querySelector('#sylius-variants-pricing').querySelector(selector);

      if (price !== undefined) {
        document.querySelector('.product-show-price').innerHTML = price.innerHTML;
        document.querySelector('button[type=submit]').removeAttribute('disabled');
      } else {
        document.querySelector('.product-show-price').innerHTML = document.querySelector('#sylius-variants-pricing').getAttribute('data-unavailable-text');
        document.querySelector('button[type=submit]').setAttribute('disabled', 'disabled');
      }
    });
  });
};

const SyliusVariantsPrices = () => {
  const syliusVariantsPricing = document.getElementById('sylius-variants-pricing') || null;
  const syliusProductVariants = document.getElementById('sylius-product-variants') || null;

  if (syliusVariantsPricing && !syliusProductVariants) {
    displayFirstAvailableVariant();
    handleProductOptionsChange();
  } else if (syliusProductVariants) {
    handleProductVariantsChange();
  }
};

export default SyliusVariantsPrices;
