import axiosApi from '@assets/js/axios-api';

function Init() {
  const returnSearch = document.querySelector('.js-return-search');
  const returnSearchUrl = returnSearch.dataset.search;
  const returnSearchButton = document.querySelector('.js-return-search-button');
  const returnSearchInput = returnSearch.querySelector('.js-return-search-input');
  const cardReturnOrderSearch = document.querySelectorAll('.js-button-return-order');
  const form = document.querySelector('#form-return');

  returnSearchInput.addEventListener('input', function() {
    removeErrorOrderId(this.parentElement);
    orderNotFound();
  });

  function removeErrorOrderId(field) {
    const spanError = field.querySelector('.ftr-field__error:not(.js-order-not-found):not(.js-order-canceled)');

    field.classList.remove('error');
    if (spanError) {
      spanError.parentNode.removeChild(spanError);
    }
  }

  function showSearchOrders(show = true) {
    const divSearchOrders = document.querySelector('.js-container-search');
    const divReturn = document.querySelector('.js-container-return');
    if (!show) {
      divSearchOrders.classList.add('ftr-hidden');
      divReturn.classList.remove('ftr-hidden');
      history.pushState({}, document.title, window.location.href + '#return-itens');
    } else {
      divSearchOrders.classList.remove('ftr-hidden');
      divReturn.classList.add('ftr-hidden');
    }
  }

  function orderNotFound(show = false) {
    const spanNotFound = document.querySelector('.js-order-not-found');
    if (!show) {
      if (!spanNotFound.classList.contains('hidden')) {
        spanNotFound.classList.add('ftr-hidden');
      }
    } else {
      spanNotFound.classList.remove('ftr-hidden');
    }
  }

  function orderCanceled(show = false) {
    const divCanceled = document.querySelector('.js-order-canceled');
    if (!show) {
      divCanceled.classList.add('ftr-hidden');
    } else {
      divCanceled.classList.remove('ftr-hidden');
    }
  }

  function renderProducts(orderProducts) {
    const containerProducts = document.querySelector('.js-container-products');
    let htmlProduct = '';

    orderProducts.map(product => {
      let {
        id,
        product_id,
        name,
        quantity,
        quantidade,
        thumb,
        color_description,
        color_template_description,
        size_description,
        size_template_description,
        specification_template_description,
        specification_description,
        model_value_on_screen,
        itens_kit,
      } = product;

      color_description = color_description || '';
      size_description = size_description || '';
      specification_description = specification_description || '';
      itens_kit = itens_kit || '';

      htmlProduct += `
        <div class="ftr-h--full js-product">
          <input
            class="ftr-radio js-product-radio js-product-radio-main"
            id="return-radio-${product_id || id}"
            type="radio"
            name="product_radio_id"
            value="${product_id || id}"
            data-quantity="${quantity || quantidade}"
          >
          <label class="ftr-radio-label ftr-out-space--v-n" for="return-radio-${product_id || id}" style="width: 100%">
            <div class="ftr-product-card__content">
              <div class="ftr-product-card__image">
                <picture>
                  <source srcset="${thumb.webp}">
                  <img width="68" height="68" src="${thumb.jpg}" alt="${name}">
                </picture>
              </div>
              <div class="ftr-product-card__info">
                <span class="ftr-text--s ftr-block ftr-text--grey">
                  (${language.getText('return', 'text_codigo_item')} ${model_value_on_screen})
                </span>
                <span class="ftr-text--m ftr-block ftr-text-dark">${name}</span>
                ${color_description &&
                  `
                  <span class="ftr-text--s ftr-text--grey">${color_template_description}</span>
                  <span class="ftr-text--m ftr-text-dark">${color_description}</span>
                `}
                ${size_description &&
                  `
                  <span class="ftr-text--s ftr-text--grey">${size_template_description}</span>
                  <span class="ftr-text--m ftr-text-dark">${size_description}</span>
                `}
                ${specification_description &&
                  `
                  <span class="ftr-text--s ftr-text--grey">${specification_template_description}</span>
                  <span class="ftr-text--m ftr-text-dark">${specification_description}</span>
                `}
                ${itens_kit &&
                  `
                  <input class="ftr-check js-product-kit-entry" id="return-check-${product_id || id}" type="checkbox">
                  <label class="ftr-check-label" for="return-check-${product_id || id}">
                    <span class="ftr-check-label__text">Devolver um produto específico do kit</span>
                  </label>
                `}
              </div>
            </div>
          </label>
          ${itens_kit &&
            `
            <div class="js-product-kit-container ftr-hidden">
              <span class="ftr-text--s ftr-block">Qual produto você quer devolver?</span>
              ${itens_kit
                .map(
                  item => `
                  <input class="ftr-radio js-product-radio" id="${item.product_id}" type="radio" name="product_radio_id" value="${item.product_id}" data-quantity="${item.quantidade}">
                  <label class="ftr-radio-label" for="${item.product_id}">
                    <span class="ftr-radio-label__text">${item.descricao}</span>
                  </label>
              `
                )
                .join('')}
            </div>
          `}
          <label class="ftr-field ftr-hidden js-product-quantity">
            <input
              type="number"
              name="quantity_${product_id || id}"
              class="ftr-field__entry ftr-js-field__entry mask-int js-product-quantity-entry"
              min="1"
              max="1"
              value="1"
            >
            <span class="ftr-field__text">${language.getText('return', 'entry_quantity')}</span>
          </label>
        </div>
        <hr class="ftr-out-space--v-xl" />
      `;
    });

    containerProducts.innerHTML = htmlProduct;
    const products = containerProducts.querySelectorAll('.js-product');

    products.forEach(product => {
      const entryProductKit = product.querySelector('.js-product-kit-entry');
      if (entryProductKit) {
        entryProductKit.addEventListener('change', event => {
          const containerProductKit = product.querySelector('.js-product-kit-container');
          if (event.target.checked) {
            containerProductKit.classList.remove('ftr-hidden');
            const firstRadio = containerProductKit.querySelector('.js-product-radio');
            firstRadio.checked = true;
            firstRadio.dispatchEvent(new Event('change'));
          } else {
            containerProductKit.classList.add('ftr-hidden');
            product.querySelector('.js-product-radio-main').checked = true;
          }
        });
      }

      const radios = product.querySelectorAll('.js-product-radio');
      radios.forEach(radio => {
        const quantity = radio.dataset.quantity;
        radio.addEventListener('change', () => {
          if (radio.classList.contains('js-product-radio-main')) {
            document.querySelectorAll('.js-product-kit-entry').forEach(item => {
              item.checked = false;
            });
            document.querySelectorAll('.js-product-kit-container').forEach(item => {
              item.classList.add('ftr-hidden');
            });
          }
          const allContainerProductQuantity = containerProducts.querySelectorAll('.js-product-quantity');
          allContainerProductQuantity.forEach(item => {
            item.classList.add('ftr-hidden');
          });

          const selectedProductQuantityEntry = product.querySelector('.js-product-quantity-entry');
          selectedProductQuantityEntry.name = `quantity_${radio.value}`;
          selectedProductQuantityEntry.value = 1;
          selectedProductQuantityEntry.max = quantity;

          const selectedContainerProductQuantity = product.querySelector('.js-product-quantity');
          selectedContainerProductQuantity.classList.remove('ftr-hidden');
        });
      });
    });
  }

  function alreadySelectedProduct() {
    const form = document.querySelector('form[data-product-id]');
    if (!form) return;
    const productId = form.dataset.productId;
    if (!productId) return;

    const radio = document.querySelector(`input[value='${productId}']`);

    radio.checked = true;
    const containerProduct = radio.closest('.js-product');
    containerProduct.querySelector('.js-product-quantity').classList.remove('ftr-hidden');

    const containerProductKit = radio.closest('.js-product-kit-container');
    if (containerProductKit) {
      containerProductKit.classList.remove('ftr-hidden');
      containerProduct.querySelector('.js-product-kit-entry').checked = true;
    }
  }

  function returnOrder(searchValue, context) {
    context = context || returnSearchButton;

    if (context.classList.contains('disabled')) {
      return;
    }

    for (let card of cardReturnOrderSearch) {
      card.classList.add('disabled');
    }
    returnSearchButton.disabled = true;

    axiosApi({
      method: 'get',
      url: returnSearchUrl,
      params: { search: searchValue },
    })
      .then(({ data }) => {
        const { order, orderProducts } = data;

        if (order && orderProducts) {
          if (order.status_futuraserver == Type_PedidoStatus.TpPSt_Cancelado) {
            orderNotFound();
            orderCanceled(true);
          } else {
            orderCanceled();

            renderProducts(orderProducts);
            showSearchOrders(false);
            alreadySelectedProduct();

            let input = returnSearch.querySelector('.js-return-search-input');
            input.value = searchValue;
            input.classList.add('on');
            input.classList.remove('off');

            removeErrorOrderId(input.parentElement);
            orderNotFound();
          }
        } else {
          orderCanceled();
          orderNotFound(true);
        }
      })
      .catch(err => {
        console.log(err);
      })
      .finally(() => {
        for (let card of cardReturnOrderSearch) {
          card.classList.remove('disabled');
        }
        returnSearchButton.disabled = false;
      });
  }

  for (let card of cardReturnOrderSearch) {
    const searchValue = card.dataset.returnOrderId;
    card.addEventListener('click', function() {
      returnOrder(searchValue, this);
    });
  }

  returnSearchButton.addEventListener('click', () => {
    const searchValue = returnSearchInput.value;
    returnOrder(searchValue);
  });

  const order_id = form.dataset.orderId;
  if (order_id) {
    returnOrder(order_id);
  }

  window.onpopstate = function(event) {
    showSearchOrders(true);
  };

  $('.ftr-js-privacy-policy').one('click', function(event) {
    event.preventDefault();
    $('.ftr-loading-bar').removeClass('ftr-none');
    $.ajax({
      url: $(this).attr('href'),
      dataType: 'html',
    })
      .done(function(data) {
        $('.ftr-js-privacy-policy-container').append(data);
      })
      .fail(function() {
        console.log('error');
      })
      .always(function() {
        $('.ftr-loading-bar').addClass('ftr-none');
      });
  });
}

if (document.readyState === 'loading') {
  // Ainda carregando
  document.addEventListener('DOMContentLoaded', Init);
} else {
  // `DOMContentLoaded` foi disparado
  Init();
}
