import axios from 'axios';
import documentReady from '@assets/js/documentReady';
import SelectAutocomplete from '../../select-autocomplete';
import googleAnalytics from '@assets/js/googleAnalytics';
import { renderHtml } from '@assets/js/helpers';

window.productJsInit = () => {
  const DATA_INFO = JSON.parse(document.querySelector('[data-info]').getAttribute('data-info'));

  const SELECT_COLORS = document.getElementById('colors'),
    SELECT_SIZES = document.getElementById('sizes'),
    SELECT_SPECIFICATIONS = document.getElementById('specifications'),
    GRID_OPTION = document.querySelectorAll('.js-grid-option');

  if (SELECT_COLORS) {
    new SelectAutocomplete(SELECT_COLORS, function() {
      if (SELECT_COLORS.value !== this.value) {
        setGrid('color_id', this.value);
      }
    });
  }

  if (SELECT_SIZES) {
    new SelectAutocomplete(SELECT_SIZES, function() {
      setGrid('size_id', this.value);
    });
  }

  if (SELECT_SPECIFICATIONS) {
    new SelectAutocomplete(SELECT_SPECIFICATIONS, function() {
      setGrid('specification_id', this.value);
    });
  }

  if (GRID_OPTION) {
    for (let i = 0; i < GRID_OPTION.length; i++) {
      const TYPE = GRID_OPTION[i].dataset.caracteristica,
        ID = GRID_OPTION[i].dataset.id;
      GRID_OPTION[i].onclick = () => setGrid(TYPE, ID);
    }
  }

  const productPageLoading = document.createElement('div');
  productPageLoading.classList.add('product-page-loading', 'hidden');

  const container = document.querySelector('#product-content');
  container.appendChild(productPageLoading);

  function setGrid(type, id) {
    const BTN_CART = document.querySelector('.js-product-container-action .js-btn-cart');

    let data = BTN_CART ? JSON.parse(BTN_CART.getAttribute('data-grid')) : {};

    data['product_id'] = DATA_INFO.productId;
    data[type] = id;

    if (typeof DATA_INFO.route2 != 'undefined') {
      data['route2'] = DATA_INFO.route2;
    }

    const time = setTimeout(() => {
      productPageLoading.classList.remove('hidden');
    }, 800);

    axios({
      method: 'get',
      url: 'index.php?route=product/product/getProductGridLink&ajax=1',
      params: data,
    })
      .then(({ data }) => {
        const { url, html } = data;

        if (url && html) {
          const renderedHtml = renderHtml(html);
          window.initActionProductBox(renderedHtml);
          window.initCountdown(renderedHtml);

          container.parentNode.insertBefore(renderedHtml, container);
          container.parentNode.removeChild(container);
          window.productJsInit();
          window.pageProductJsInit();
          history.replaceState(null, null, url.replace(/(&amp;)/g, '&').replace('&ajax=1', ''));
        }
      })
      .catch(console.log)
      .finally(() => {
        clearTimeout(time);
        productPageLoading.classList.add('hidden');
      });
  }

  googleAnalytics('view_item', {
    currency: 'BRL',
    items: [
      {
        item_id: DATA_INFO.productId,
        item_name: DATA_INFO.productName,
        item_brand: DATA_INFO.productBrand,
        price: DATA_INFO.value,
        currency: 'BRL',
        quantity: 1,
      },
    ],
  });
};

documentReady(window.productJsInit);
