import documentReady from '@assets/js/documentReady';
import FixedContentOnScroll from '../../fixed-content';
import axiosApi from '@assets/js/axios-api';

documentReady(() => {
  window.language.load('account/return');
  new FixedContentOnScroll(document.querySelector('.js-fixed-on-top'), {
    discountTop: [document.querySelector('.js-header__main')],
  });

  const section = document.querySelector('#return-form-info');

  const buttonsReturnOrder = document.querySelectorAll('.js-button-return-order');
  buttonsReturnOrder.forEach(button => {
    const searchValue = button.dataset.returnOrderId;
    button.addEventListener('click', () => returnOrder(searchValue));
  });

  function showSearchOrders(show = true) {
    const divSearchOrders = document.querySelector('.js-container-search');
    const divReturn = document.querySelector('.js-container-return');
    if (!show) {
      divSearchOrders.classList.add('hidden');
      divReturn.classList.remove('hidden');
    } else {
      divSearchOrders.classList.remove('hidden');
      divReturn.classList.add('hidden');
    }
  }

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

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

  function handleBackButton() {
    const backButton = document.querySelector('.js-back-to-search');
    const divSearchOrders = document.querySelector('.js-container-search');
    backButton.addEventListener('click', event => {
      if (divSearchOrders.classList.contains('hidden')) {
        event.preventDefault();
      }
      showSearchOrders(true);
    });
  }

  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="vertical-padding-small js-product">
        <label class="radio radio-small">
          <input class="radio-entry js-product-radio js-product-radio-main" type="radio" name="product_radio_id"
            value="${product_id || id}"
            data-quantity="${quantity || quantidade}"
          >
          <span class="radio-text">
            <div class="row x-small-space-xs no-space-md middle-xs between-xs">
              <div class="col-xs-12 col-md">
                <div class="content-box flex nowrap-xs middle-xs">
                  <div>
                    <picture>
                      <source srcset="${thumb.webp}">
                      <img src="${thumb.jpg}" alt="${name}">
                    </picture>
                  </div>
                  <div class="full-width left-margin-medium">
                    <span class="visible-block text-small text-small text-word-wrap bottom-margin-x-small">
                      (${window.language.get('text_codigo_item')} ${model_value_on_screen})
                    </span>
                    <span class="visible-block text-medium text-dark text-bold bottom-margin-x-small">${name}</span>
                      ${color_description &&
                        `
                        <span class="text-small text-gray">${color_template_description}</span>
                        <span class="text-small text-dark text-bold">${color_description}</span>
                      `}
                      ${size_description &&
                        `
                        <span class="text-small text-gray">${size_template_description}</span>
                        <span class="text-small text-dark text-bold">${size_description}</span>
                      `}
                      ${specification_description &&
                        `
                        <span class="text-small text-gray">${specification_template_description}</span>
                        <span class="text-small text-dark text-bold">${specification_description}</span>
                      `}
                      ${itens_kit &&
                        `
                        <label class="checkbox checkbox-small">
                          <input class="checkbox-entry js-product-kit-entry" type="checkbox">
                          <span class="checkbox-text">Devolver um produto específico do kit</span>
                        </label>
                      `}
                  </div>
                </div>
              </div>
              <div class="col-xs-12 col-md-2 hidden js-product-quantity">
                <div class="content-box">
                  <label class="field field-medium left-margin-small">
                    <span class="field-label">
                      ${window.language.get('entry_quantity')}
                    </span>
                    <input
                      class="field-entry mask-int js-product-quantity-entry"
                      type="number"
                      name="quantity_${product_id || id}"
                      min="1"
                      max="1"
                      value="1"
                      maxlength="96"
                    >
                  </label>
                </div>
              </div>
            </div>
          </span>
        </label>
        ${itens_kit &&
          `
          <div class="bottom-padding-medium bottom-border-gray js-product-kit-container hidden">
            <span class="visible-block text-small text-bold text-dark bottom-margin-small">Qual produto você quer devolver?</span>
            ${itens_kit
              .map(
                item => `
                <label class="radio radio-small">
                  <input class="radio-entry js-product-radio" type="radio" name="product_radio_id" value="${item.product_id}" data-quantity="${item.quantidade}">
                  <span class="radio-text">${item.descricao}</span>
                </label>
            `
              )
              .join('')}
          </div>
        `}
      </div>
      `;
    });

    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('hidden');
            const firstRadio = containerProductKit.querySelector('.js-product-radio');
            firstRadio.checked = true;
            firstRadio.dispatchEvent(new Event('change'));
          } else {
            containerProductKit.classList.add('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('hidden');
            });
          }
          const allContainerProductQuantity = containerProducts.querySelectorAll('.js-product-quantity');
          allContainerProductQuantity.forEach(item => {
            item.classList.add('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('hidden');
        });
      });
    });
  }

  const returnSearch = document.querySelector('.js-return-search');
  const returnSearchUrl = returnSearch.dataset.search;
  const returnSearchButton = returnSearch.querySelector('.js-return-search-button');
  const returnSearchInput = returnSearch.querySelector('.js-return-search-input');

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

  function returnOrder(searchValue) {
    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);
            orderNotFound();
            showSearchOrders(false);
            handleBackButton();
            alreadySelectedProduct();

            let input = returnSearch.querySelector('.js-return-search-input');
            input.value = searchValue;
          }
        } else {
          orderCanceled();
          orderNotFound(true);
        }
      })
      .catch(err => {
        console.log(err);
      });
  }

  function alreadySelectedProduct() {
    const productId = section.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('hidden');

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

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